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

210
LINES

< > BotCompany Repo | #1027734 - Cruddie [backup before changing cookie handling]

JavaX source code (Dynamic Module) [tags: use-pretranspiled] - run with: Stefan's OS

Uses 911K of libraries. Click here for Pure Java version (19600L/114K).

!7

concept StandardScript {
  S scriptID;
}

cmodule Cruddie > DynPrintLogAndEnabled {
  !include #1027628 // HTTP+HTTPS servers
  
  transient S salt;
  transient WebChatBot chatBot;
  transient CRUD<StandardScript> standardScriptsCRUD;
  transient CRUD<Conversation> conversationsCRUD;
  
  S myLink() { ret "https://cruddie.site/"; }
  S botLink() { ret "bot"; /*ret appendWithSlash(myLink(), "bot");*/ }
  
  switchable S frontendModuleLibID = "#1027675/ChatBotFrontend";
  switchable S backendModuleLibID = "#1027591/DynamicClassesMultiCRUD";
  transient S cmdsSnippetID = #1027616;

  start {
    standardScriptsCRUD = new CRUD(StandardScript);
    conversationsCRUD = new CRUD(Conversation);
    thread {
      File saltFile = secretProgramFile("salt.txt");
      S salt = trimLoadTextFile(saltFile);
      if (empty(salt)) {
        saveTextFile(saltFile, salt = randomID());
        print("Made salt"); 
      }
      dm_restartOnFieldChange enabled();
      if (!enabled) ret;
      chatBot = new WebChatBot;
      chatBot.preprocess = s -> {
        S s2 = googleDecensor(s);
        print("Preprocessing: " + s + " => " + s2);
        ret s2;
      };
      chatBot.templateID = #1027690;
      chatBot.baseLink = botLink();
      chatBot.thoughtBot = new ThoughtBot;
      
      chatBot.jsOnMsgHTML = "window.processNewStuff(src);";
      
      chatBot.onBotShown = [[ {
        var input = $("#status_message")[0];
        console.log("input: " + input);
        if (input)
          new Awesomplete(input, {
            minChars: 1,
            list: [
              "I call you Fido",
              "What is your name?",
              'add script "#1027704/SomeCruddieScripts/RepeatAfterMe"',
              'add script "#1027704/SomeCruddieScripts/GoPublic"',
              'clear scripts'
            ]
          });
      } ]];
      
      chatBot.afterHeading = "` + ('webkitSpeechRecognition' in window ? ` &nbsp; " + tag("button", "...", onclick := "startOrStop(); if (bigOn) startVAD(); else stopVAD();", type := 'button, class := 'speechOnBtn, disabled := 'disabled, display := 'inline)
        /*+ hjs([[console.log("Updating"); window.srUpdate();]])*/ + "` : ``) + `"
        + hdiv(hsnippetimg(#1102908, width := 24, height := 24, title := "Someone is speaking (either me or you)"), style := "display: inline; visibility: hidden; margin-left: 10px", class := "vadStatus")
        + hdiv(hsnippetimg(#1102909, width := 24, height := 24, title := "Listening"), style := "display: inline; visibility: hidden; margin-left: 10px", class := "listenStatus")
        + hdiv(small("Note: All conversations are public rn " + targetBlank("https://www.youtube.com/watch?v=StxQerL0D-o", "(why)")));
        
      chatBot.moreStuff = "window.srUpdate();";
  
      chatBot.start();
      
      set redirectHttpToHttps;
      start_webServers(javaxSecretDir("cruddie.site/keystore.p12"), "botcompany");
    }
  }

  O webServe(S uri, SS params) {
    printVars("webServe", +uri);
    //S cookie = serveHttp_cookieHandling();
    new Matches m;
    S uri2 = appendSlash(uri);
    if (startsWith(uri2, "/bot/", m))
      ret chatBot.html("/" + m.rest(), params);
    if (eq(uri, "/awesomplete.css")) ret serveWithContentType(loadSnippet(#2000595), "text/css");
    if (eq(uri, "/awesomplete.js")) ret serveText(loadSnippet(#2000594));
      
    S jsOnSpeech = "if (transcript != 'stop listening') window.submitAMsg(transcript);";
    
    S sayBotMsgsScript = [[
      window.processNewStuff = function(src) {
      ]] + (eq(params.get('quiet), "1") ? "" : [[
        if ($("#speechResults") == null) return; // no speech
        // we assume that webkit speech synthesis is present
        // when there is webkit speech recognition
        if (!bigOn) return; // not enabled
        console.log("Got speech");
        var match = src.match(/\d+/);
        if (match == null) return;
        if (src.match(/NEW DIALOG -->/)) return;
        console.log("Got incremental");
        var re = /bot-utterance">(.*?)</g;
        var match = re.exec(src);
        var lastUtterance = null;
        while (match != null) {
          lastUtterance = match[1];
          match = re.exec(src);
        }
        // TODO: properly drop HTML tags/HTML-decode
        if (lastUtterance)
          say(lastUtterance);
      ]]) + [[
      };
    ]];
    
    S speechUI = "";
      /*hdiv(
        "&lt; Talk to me &gt;",
        id := 'speechResults,
        style := "margin: 10px");*/
      
    ret hhtml(hmobilefix() + hhead(
        htitle("CRUDDIE - I manage your anything")
      + hLoadJQuery2()
      + hJsMakeCookie()
      + [[<link rel="stylesheet" href="awesomplete.css" /><script src="awesomplete.js"></script>]] // took out async
      )
      + hbody(hOnBottom(
        p(hsnippetimage(#1102905))
      + p("Chat bot is doing basic stuff. Documentation coming up.")
      + stats()
      + hjavascript([[
        var srPause;
        
        function say(text) {
          console.log("Saying: " + text);
          var u = new SpeechSynthesisUtterance(text);
          u.onstart = function() { console.log("speech start"); srPause = true; srUpdate(); };
          u.onend = function() { srPause = false; srUpdate(); };
          window.speechSynthesis.speak(u);
        }
      ]] + sayBotMsgsScript)
      + hSpeechRecognition(jsOnSpeech, true, "en-US", false,
        noWebKit := p("Use Chrome if you want speech recognition"),
        +speechUI)
      + hjs((S) chatBot.html("/", litmap(), returnJS := true))
      + hVAD(
        [[console.log("voice start"); $(".vadStatus").css("visibility", "visible");]],
        [[console.log("voice stop"); $(".vadStatus").css("visibility", "hidden");]],
        false)
      )/*, onLoad := "startAwesomplete()"*/));
  }
  
  S cookieToCaseID(S cookie) {
    ret md5(cookie + salt);
  }
  
  class Request {
    S cookie, caseID;
    S frontend, backend; // module IDs
    
    *(S *cookie) {
      caseID = cookieToCaseID(cookie);
      frontend = dm_makeModuleWithParams_systemQ(frontendModuleLibID, +caseID);
      backend = dm_makeModuleWithParams_systemQ(backendModuleLibID, +caseID);
      dm_call(frontend, 'connectToBackend, backend);
      dm_call(frontend, 'importCmdsFromSnippetIfEmpty, cmdsSnippetID);
      dm_call(frontend, 'addScripts, collect scriptID(list StandardScript()));
      Conversation conv = uniq Conversation(+cookie);
      forwardSwappableFunctionToObject(dm_mod(frontend),
        'chatLog_userMessagesOnly, func -> LS {
          map(m -> m.text, filter(conv.allMsgs(), m -> m.fromUser))
        }, 'get);
      printVars(+caseID, +backend);
    }
  }
  
  class ThoughtBot {
    new ThreadLocal<Request> request;
    
    void setSession(S cookie, SS params) {
      //session.set(uniq_sync(Session, +cookie));
      request.set(new Request(cookie));
    }
    
    S initialMessage() {
      //ret "Hello from module " + request->backend;
      ret (S) dm_call(request->backend, 'answer, "stats");
    }
    
    S answer(S s) {
      ret (S) dm_call(request->frontend, 'answer, s);
    }
  }
  
  S stats() {
    ret p(joinWithBR(
      "Server temperature is " + dm_cpuTemperature(),
      n2(numberOfCruddies(), "cruddie") + ", " + n2(vmBus_countResponses chatBotFrontend()) + " loaded",
    ));
  }
  
  int numberOfCruddies() {
    ret countDirsInDir(getProgramDir(beforeSlash(frontendModuleLibID)));
  }
  
  visual
    jtabs("Main", super,
      "Standard Scripts", standardScriptsCRUD.visualize(),
      "Conversations", conversationsCRUD.visualize());
}

Author comment

Began life as a copy of #1027610

download  show line numbers  debug dex   

Travelled to 6 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, xrpafgyirdlv

No comments. add comment

Snippet ID: #1027734
Snippet name: Cruddie [backup before changing cookie handling]
Eternal ID of this version: #1027734/1
Text MD5: 6ab1a5a2047bed8727c6d029be3782cb
Transpilation MD5: 2e9c5ce050655a6be6cb27eeac07a833
Author: stefan
Category:
Type: JavaX source code (Dynamic Module)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2020-04-09 12:26:06
Source code size: 7769 bytes / 210 lines
Pitched / IR pitched: No / No
Views / Downloads: 22 / 40
Referenced in: [show references]

Formerly at http://tinybrain.de/1027734 & http://1027734.tinybrain.de