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

194
LINES

< > BotCompany Repo | #1027705 // Cruddie [backup before "all public" notice]

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

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

1  
!7
2  
3  
concept StandardScript {
4  
  S scriptID;
5  
}
6  
7  
cmodule Cruddie > DynPrintLogAndEnabled {
8  
  !include #1027628 // HTTP+HTTPS servers
9  
  
10  
  transient S salt;
11  
  transient WebChatBot chatBot;
12  
  transient CRUD<StandardScript> standardScriptsCRUD;
13  
  
14  
  S myLink() { ret "https://cruddie.site/"; }
15  
  S botLink() { ret "bot"; /*ret appendWithSlash(myLink(), "bot");*/ }
16  
  
17  
  switchable S frontendModuleLibID = "#1027675/ChatBotFrontend";
18  
  switchable S backendModuleLibID = "#1027591/DynamicClassesMultiCRUD";
19  
  transient S cmdsSnippetID = #1027616;
20  
21  
  start {
22  
    standardScriptsCRUD = new CRUD(StandardScript);
23  
    thread {
24  
      File saltFile = secretProgramFile("salt.txt");
25  
      S salt = trimLoadTextFile(saltFile);
26  
      if (empty(salt)) {
27  
        saveTextFile(saltFile, salt = randomID());
28  
        print("Made salt"); 
29  
      }
30  
      dm_restartOnFieldChange enabled();
31  
      if (!enabled) ret;
32  
      chatBot = new WebChatBot;
33  
      chatBot.templateID = #1027690;
34  
      chatBot.baseLink = botLink();
35  
      chatBot.thoughtBot = new ThoughtBot;
36  
      
37  
      chatBot.jsOnMsgHTML = "window.processNewStuff(src);";
38  
      
39  
      chatBot.onBotShown = [[ {
40  
        var input = $("#status_message")[0];
41  
        console.log("input: " + input);
42  
        if (input)
43  
          new Awesomplete(input, {
44  
            minChars: 1,
45  
            list: [
46  
              "I call you Fido",
47  
              "What is your name?",
48  
              'add script "#1027704/SomeCruddieScripts/RepeatAfterMe"',
49  
              'add script "#1027704/SomeCruddieScripts/GoPublic"',
50  
              'clear scripts'
51  
            ]
52  
          });
53  
      } ]];
54  
      
55  
      chatBot.afterHeading = "` + ('webkitSpeechRecognition' in window ? ` &nbsp; " + tag("button", "...", onclick := "startOrStop(); startVAD();", type := 'button, class := 'speechOnBtn, disabled := 'disabled, display := 'inline)
56  
        /*+ hjs([[console.log("Updating"); window.srUpdate();]])*/ + "` : ``) + `"
57  
        + hdiv(hsnippetimg(#1102909, width := 24, height := 24, title := "Listening"), style := "display: inline; visibility: hidden; margin-left: 10px", class := "listenStatus")
58  
        + hdiv(hsnippetimg(#1102908, width := 24, height := 24, title := "Voice activity detected"), style := "display: inline; visibility: hidden; margin-left: 10px", class := "vadStatus");
59  
        
60  
      chatBot.moreStuff = "window.srUpdate();";
61  
  
62  
      chatBot.start();
63  
      
64  
      set redirectHttpToHttps;
65  
      start_webServers(javaxSecretDir("cruddie.site/keystore.p12"), "botcompany");
66  
    }
67  
  }
68  
69  
  O webServe(S uri, SS params) {
70  
    printVars("webServe", +uri);
71  
    //S cookie = serveHttp_cookieHandling();
72  
    new Matches m;
73  
    S uri2 = appendSlash(uri);
74  
    if (startsWith(uri2, "/bot/", m))
75  
      ret chatBot.html("/" + m.rest(), params);
76  
    if (eq(uri, "/awesomplete.css")) ret serveWithContentType(loadSnippet(#2000595), "text/css");
77  
    if (eq(uri, "/awesomplete.js")) ret serveText(loadSnippet(#2000594));
78  
      
79  
    S jsOnSpeech = "if (transcript != 'stop listening') window.submitAMsg(transcript);";
80  
    
81  
    S sayScript = [[
82  
      window.processNewStuff = function(src) {
83  
        if ($("#speechResults") == null) return; // no speech
84  
        // we assume that webkit speech synthesis is present
85  
        // when there is webkit speech recognition
86  
        if (!bigOn) return; // not enabled
87  
        console.log("Got speech");
88  
        var match = src.match(/\d+/);
89  
        if (match == null) return;
90  
        if (src.match(/NEW DIALOG -->/)) return;
91  
        console.log("Got incremental");
92  
        var re = /bot-utterance">(.*?)</g;
93  
        var match = re.exec(src);
94  
        var lastUtterance = null;
95  
        while (match != null) {
96  
          lastUtterance = match[1];
97  
          match = re.exec(src);
98  
        }
99  
        // TODO: properly drop HTML tags/HTML-decode
100  
        if (lastUtterance)
101  
          say(lastUtterance);
102  
      };
103  
    ]];
104  
    
105  
    S speechUI =
106  
      hdiv(
107  
        "&lt; Talk to me &gt;",
108  
        id := 'speechResults,
109  
        style := "margin: 10px");
110  
      
111  
    ret hhtml(hmobilefix() + hhead(
112  
        htitle("CRUDDIE - I manage your anything")
113  
      + hLoadJQuery2()
114  
      + hJsMakeCookie()
115  
      + [[<link rel="stylesheet" href="awesomplete.css" /><script src="awesomplete.js"></script>]] // took out async
116  
      )
117  
      + hbody(hOnBottom(
118  
        p(hsnippetimage(#1102905))
119  
      + p("Chat bot is doing basic stuff. Documentation coming up.")
120  
      + stats()
121  
      + hjavascript([[
122  
        var srPause;
123  
        
124  
        function say(text) {
125  
          console.log("Saying: " + text);
126  
          var u = new SpeechSynthesisUtterance(text);
127  
          u.onstart = function() { console.log("speech start"); srPause = true; srUpdate(); };
128  
          u.onend = function() { srPause = false; srUpdate(); };
129  
          window.speechSynthesis.speak(u);
130  
        }
131  
      ]] + sayScript)
132  
      + hSpeechRecognition(jsOnSpeech, true, "en-US", false,
133  
        noWebKit := p("Use Chrome if you want speech recognition"),
134  
        +speechUI)
135  
      + hjs((S) chatBot.html("/", litmap(), returnJS := true))
136  
      + hVAD(
137  
        [[console.log("voice start"); $(".vadStatus").css("visibility", "visible");]],
138  
        [[console.log("voice stop"); $(".vadStatus").css("visibility", "hidden");]],
139  
        false)
140  
      )/*, onLoad := "startAwesomplete()"*/));
141  
  }
142  
  
143  
  S cookieToCaseID(S cookie) {
144  
    ret md5(cookie + salt);
145  
  }
146  
  
147  
  class Request {
148  
    S cookie, caseID;
149  
    S frontend, backend; // module IDs
150  
    
151  
    *(S *cookie) {
152  
      caseID = cookieToCaseID(cookie);
153  
      frontend = dm_makeModuleWithParams_systemQ(frontendModuleLibID, +caseID);
154  
      backend = dm_makeModuleWithParams_systemQ(backendModuleLibID, +caseID);
155  
      dm_call(frontend, 'connectToBackend, backend);
156  
      dm_call(frontend, 'importCmdsFromSnippetIfEmpty, cmdsSnippetID);
157  
      dm_call(frontend, 'addScripts, collect scriptID(list StandardScript()));
158  
      printVars(+caseID, +backend);
159  
    }
160  
  }
161  
  
162  
  class ThoughtBot {
163  
    new ThreadLocal<Request> request;
164  
    
165  
    void setSession(S cookie, SS params) {
166  
      //session.set(uniq_sync(Session, +cookie));
167  
      request.set(new Request(cookie));
168  
    }
169  
    
170  
    S initialMessage() {
171  
      //ret "Hello from module " + request->backend;
172  
      ret (S) dm_call(request->backend, 'answer, "stats");
173  
    }
174  
    
175  
    S answer(S s) {
176  
      ret (S) dm_call(request->frontend, 'answer, s);
177  
    }
178  
  }
179  
  
180  
  S stats() {
181  
    ret p(joinWithBR(
182  
      "Server temperature is " + dm_cpuTemperature(),
183  
      n2(numberOfCruddies(), "cruddie") + ", " + n2(vmBus_countResponses chatBotFrontend()) + " loaded",
184  
    ));
185  
  }
186  
  
187  
  int numberOfCruddies() {
188  
    ret countDirsInDir(getProgramDir(beforeSlash(frontendModuleLibID)));
189  
  }
190  
  
191  
  visual
192  
    jtabs("Main", super,
193  
      "Standard Scripts", standardScriptsCRUD.visualize());
194  
}

Author comment

Began life as a copy of #1027610

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1027705
Snippet name: Cruddie [backup before "all public" notice]
Eternal ID of this version: #1027705/1
Text MD5: 08dc45393fdf8460976a44b4adb9048c
Transpilation MD5: 7c70a9244640e1880ea1b93ecd952d4a
Author: stefan
Category:
Type: JavaX source code (Dynamic Module)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2020-04-03 16:33:59
Source code size: 6948 bytes / 194 lines
Pitched / IR pitched: No / No
Views / Downloads: 197 / 262
Referenced in: [show references]