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

227
LINES

< > BotCompany Repo | #1017946 // Telegram Facts Bot [Include, old]

JavaX fragment (include)

1  
  bool debug;
2  
  bool imagineMode;
3  
  bool collectCheckingLog = true;
4  
  new LinkedHashSet<S> imaginedFacts;
5  
  LS checkingLog;
6  
  long processingTime;
7  
  new L<IfThen> activeTempRules;
8  
  
9  
  visualize {
10  
    ret withCenteredButtons(super.visualize(),
11  
      "Checking Log", r { showText("Checking Log", lines(checkingLog)) });
12  
  }
13  
14  
  void thinkAbout(S s) {
15  
    time "Processing Time For Message"{
16  
      thinkAbout_impl(s);
17  
    }
18  
    processingTime = lastTiming();
19  
  }
20  
  
21  
  void thinkAbout_impl(S input) {
22  
    new Thinking().thinkAbout_impl(input);
23  
  }
24  
  
25  
  void _postMessage(S s) { postMessage(s); }
26  
  
27  
  class Thinking {
28  
    long cancelTime = now()+20000;
29  
    new Map<S, Int> ruleScores;
30  
    new LinkedHashSet<S> rewrittenInputs;
31  
    new LinkedHashSet<S> newRewrittenInputs;
32  
    volatile bool posted, done;
33  
    new L<IfThen> rules;
34  
    replace Plan with PlanInMotion.
35  
    new Plan<Runnable> plan;
36  
    
37  
    void postMessage(S s) {
38  
      _postMessage(s);
39  
      posted = true;
40  
    }
41  
    
42  
    void done() { done = true; }
43  
    
44  
    O evalExp(NLLogicChecker_v2 c, Exp e, NLLogicChecker_v2.Matching m) {
45  
      // prepare context
46  
      final SS vars = m.matches;
47  
      temp tempSetThreadLocal(ai_context_tl(), new O {
48  
        LS getList(S var) {
49  
          int i = 1;
50  
          S s;
51  
          new LS l;
52  
          while ((s = vars.get(var + i++)) != null)
53  
            l.add(s);
54  
          ret l;
55  
        }
56  
        
57  
        IfThen getRule(S id) {
58  
          ret findByField(rules, globalID := id);
59  
        }
60  
      });
61  
  
62  
      S code = nlLogic_text(e);
63  
      print("Eval'ing: " + code);
64  
      temp tempAdd(hotwire_copyOver_after, voidfunc(Class c) {
65  
        copyFields(mc(), c, 'telegram_msg_tl, 'telegram_recentHistory_tl, 'ai_context_tl)
66  
      });
67  
      O result = evalWithDollarVars(code, m.matches);
68  
      print("Result: " + shorten(str(result), 100));
69  
      ret result;
70  
    }
71  
72  
    void thinkAbout_impl(fS input1) {
73  
      plan.add(r "!initiative" {
74  
        if (!eq(input1, "!initiative")) ret;
75  
        L<IfThen> rules = mL_parsedNLRulesWithoutIDs("Initiative rules");
76  
        for (IfThen rule : shuffledIterator(rules)) {
77  
          Pair<Exp> p = nlLogic_extractFirstCondition(rule.in);
78  
          if (p == null) continue;
79  
          if (nlLogic_isFunc(p.a, 'initiative)) {
80  
            postMessage(nlLogic_text(((Func) p.a).arg));
81  
            IfThen temp = IfThen(p.b, rule.out);
82  
            temp.globalID = aGlobalID();
83  
            print("Have temp rule: " + sfu(temp));
84  
            activeTempRules.add(temp);
85  
            ret with done();
86  
          }
87  
        }
88  
        ret with done();
89  
      });
90  
      
91  
      plan.add(r "!step" {
92  
        new Matches mm;
93  
        if (!startsWith_trim(input1, "!step ", mm)) ret;
94  
        // TODO
95  
      });
96  
      
97  
      runPlanWithCheck(plan, func -> bool { !done });
98  
      if (done) ret;
99  
      
100  
      S input2 = input1;
101  
      final new LS options;
102  
      if (startsWith(input2, "[")) {
103  
        addAll(options, leadingSquareBracketOptions(input2));
104  
        input2 = dropLeadingSquareBracketStuff(input2);
105  
      }
106  
      
107  
      fS input = input2;
108  
      ai_tg_collectRuleFeedback(ruleScores, null);
109  
      
110  
      newRewrittenInputs.add(input);
111  
      final Map msg = telegram_msg();
112  
      
113  
      final NLLogicChecker_v3 c = new NLLogicChecker_v3 {
114  
        bool checkExpression_impl(Exp e, Matching m) {
115  
          if (e instanceof Literal) {
116  
            // TEXT CONDITIONS
117  
            
118  
            S text = nlLogic_text(e);
119  
            if (eq(text, "authorized"))
120  
              ret telegram_amIAuthorized();
121  
            else if(eq(text, "imagineMode"))
122  
              ret imagineMode;
123  
          }
124  
          
125  
          ret super.checkExpression_impl(e, m);
126  
        }
127  
      };
128  
129  
      c.evaluator = func(Exp e, NLLogicChecker_v2.Matching m) -> O { evalExp(c, e, m) };
130  
      
131  
      if (collectCheckingLog) {
132  
        checkingLog = new L;
133  
        nlLogic_collectCheckingLog(c, checkingLog);
134  
      }
135  
      
136  
      Pair<L<IfThen>, LS> rulesAndFacts = getRulesAndFacts();
137  
      c.facts = reversed(rulesAndFacts.b);
138  
      rules = concatLists_conservative(activeTempRules, reversed(rulesAndFacts.a)); // latest rules first!
139  
      activeTempRules.clear();
140  
141  
      while (!posted && now() < cancelTime && nempty(newRewrittenInputs)) {
142  
        fS s = first(newRewrittenInputs);
143  
        rewrittenInputs.add(s);
144  
        newRewrittenInputs.remove(s);
145  
      
146  
        c.input = s;
147  
        c.recentHistory = recentHistory;
148  
        final new L<RuleWithParams> battleSpace;
149  
    
150  
        applyNLLogicFacts_v4_verbose.set(debug);
151  
        applyNLLogicFacts_v4(c, voidfunc(IfThen rule, NLLogicChecker_v2.Matching m) {
152  
          // Rule matches completely, add to battle space
153  
          
154  
          battleSpace.add(new RuleWithParams(rule, m.matches));
155  
        }, rules);
156  
        
157  
        print("Have " + n2(battleSpace, "possible rule")
158  
          + (empty(battleSpace) ? "" : ": " + joinWithComma(map(func(RuleWithParams r) -> S { r.ruleID() + "/" + toInt(ruleScores.get(r.ruleID())) }, battleSpace))));
159  
        
160  
        bool all = options.contains("all");
161  
        if (!all) nlLogic_battleItOut(battleSpace, c.facts);
162  
        
163  
        L<RuleWithParams> winners = all ? battleSpace : nlLogic_highestScore(battleSpace, ruleScores);
164  
    
165  
        fS msgGlobalID = getString(msg, 'globalID);
166  
        //print("msgGlobalID=" + msgGlobalID);
167  
        for (RuleWithParams r : winners) {
168  
          print("Firing rule " + r.rule.globalID);
169  
          
170  
          // Save rule fire
171  
          if (nempty(msgGlobalID) && nempty(r.rule.globalID)) {
172  
            S fact = format("Rule * fired on message * at *", r.rule.globalID, msgGlobalID, localDateWithMilliseconds());
173  
             if (nempty(r.matches))
174  
               fact += " with vars " + dropPrefix("lhm", struct(r.matches));
175  
            print("Saving rule fire. Mech mode: " + mechMode());
176  
            print(addToMechList("Telegram Rule Fires", print(fact)));
177  
          }
178  
          
179  
          executeRule(c, r);
180  
        }
181  
        
182  
        if (collectCheckingLog)
183  
          print("Checking log length: " + l(checkingLog));
184  
      }
185  
    }
186  
    
187  
    void executeRule(NLLogicChecker_v3 c, RuleWithParams r) {
188  
      // Execute rule
189  
      for (Exp e : nlLogic_unrollAnd(r.rule.out)) {
190  
        e = c.apply(e, r.matches);
191  
        if (e cast Func) {
192  
          S name = e.name;
193  
          if (eqOneOf(name, 'output, 'say))
194  
            postMessage(nlLogic_text(e.arg));
195  
          else if (eq(name, 'fact)) {
196  
            S fact = nlLogic_text(e.arg);
197  
            if (imagineMode) {
198  
              if (!containsNL(imaginedFacts, fact)) {
199  
                imaginedFacts.add(fact);
200  
                postMessage("Storing imaginary fact: " + fact);
201  
              }
202  
            } else if (!ai_isQuestion_2(fact) && ai_storeActualFact(fact))
203  
              postMessage("Storing fact: " + fact);
204  
          } else if (eq(name, 'storeRule)) {
205  
            S rule = nlLogic_text(e.arg);
206  
            if (!telegram_authorizedToStoreRule(rule)) continue;
207  
            rule = nlLogic_addGlobalID(rule);
208  
            if (mech_changed(appendToMechList_noUniq("NL Logic Examples", "\n" + rule)))
209  
              postMessage("Rule stored");
210  
          } else if (eq(name, 'imagineMode)) {
211  
            imagineMode = match("true", nlLogic_text(e.arg));
212  
            if (!imagineMode) imaginedFacts.clear();
213  
          } else if (eq(name, 'input)) {
214  
            S x = nlLogic_text(e.arg);
215  
            if (!rewrittenInputs.contains(x) && newRewrittenInputs.add(x))
216  
              print("New rewritten input: " + x);
217  
          } else
218  
            ret with print("Skipping rule with unknown RHS func: " + e.name);
219  
        } else
220  
          ret with print("Skipping rule with unknown RHS element: " + e);
221  
      }
222  
    }
223  
  } // end class Thinking
224  
 
225  
  Pair<L<IfThen>, LS> getRulesAndFacts() { 
226  
    ret ai_activeRulesAndFacts(imagineMode ? asList(imaginedFacts) : null);
227  
  }

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: #1017946
Snippet name: Telegram Facts Bot [Include, old]
Eternal ID of this version: #1017946/26
Text MD5: a14fe97d1536f3ecaaec168cd164ea8a
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-08-29 12:33:15
Source code size: 8058 bytes / 227 lines
Pitched / IR pitched: No / No
Views / Downloads: 364 / 802
Version history: 25 change(s)
Referenced in: [show references]