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)

  bool debug;
  bool imagineMode;
  bool collectCheckingLog = true;
  new LinkedHashSet<S> imaginedFacts;
  LS checkingLog;
  long processingTime;
  new L<IfThen> activeTempRules;
  
  visualize {
    ret withCenteredButtons(super.visualize(),
      "Checking Log", r { showText("Checking Log", lines(checkingLog)) });
  }

  void thinkAbout(S s) {
    time "Processing Time For Message"{
      thinkAbout_impl(s);
    }
    processingTime = lastTiming();
  }
  
  void thinkAbout_impl(S input) {
    new Thinking().thinkAbout_impl(input);
  }
  
  void _postMessage(S s) { postMessage(s); }
  
  class Thinking {
    long cancelTime = now()+20000;
    new Map<S, Int> ruleScores;
    new LinkedHashSet<S> rewrittenInputs;
    new LinkedHashSet<S> newRewrittenInputs;
    volatile bool posted, done;
    new L<IfThen> rules;
    replace Plan with PlanInMotion.
    new Plan<Runnable> plan;
    
    void postMessage(S s) {
      _postMessage(s);
      posted = true;
    }
    
    void done() { done = true; }
    
    O evalExp(NLLogicChecker_v2 c, Exp e, NLLogicChecker_v2.Matching m) {
      // prepare context
      final SS vars = m.matches;
      temp tempSetThreadLocal(ai_context_tl(), new O {
        LS getList(S var) {
          int i = 1;
          S s;
          new LS l;
          while ((s = vars.get(var + i++)) != null)
            l.add(s);
          ret l;
        }
        
        IfThen getRule(S id) {
          ret findByField(rules, globalID := id);
        }
      });
  
      S code = nlLogic_text(e);
      print("Eval'ing: " + code);
      temp tempAdd(hotwire_copyOver_after, voidfunc(Class c) {
        copyFields(mc(), c, 'telegram_msg_tl, 'telegram_recentHistory_tl, 'ai_context_tl)
      });
      O result = evalWithDollarVars(code, m.matches);
      print("Result: " + shorten(str(result), 100));
      ret result;
    }

    void thinkAbout_impl(fS input1) {
      plan.add(r "!initiative" {
        if (!eq(input1, "!initiative")) ret;
        L<IfThen> rules = mL_parsedNLRulesWithoutIDs("Initiative rules");
        for (IfThen rule : shuffledIterator(rules)) {
          Pair<Exp> p = nlLogic_extractFirstCondition(rule.in);
          if (p == null) continue;
          if (nlLogic_isFunc(p.a, 'initiative)) {
            postMessage(nlLogic_text(((Func) p.a).arg));
            IfThen temp = IfThen(p.b, rule.out);
            temp.globalID = aGlobalID();
            print("Have temp rule: " + sfu(temp));
            activeTempRules.add(temp);
            ret with done();
          }
        }
        ret with done();
      });
      
      plan.add(r "!step" {
        new Matches mm;
        if (!startsWith_trim(input1, "!step ", mm)) ret;
        // TODO
      });
      
      runPlanWithCheck(plan, func -> bool { !done });
      if (done) ret;
      
      S input2 = input1;
      final new LS options;
      if (startsWith(input2, "[")) {
        addAll(options, leadingSquareBracketOptions(input2));
        input2 = dropLeadingSquareBracketStuff(input2);
      }
      
      fS input = input2;
      ai_tg_collectRuleFeedback(ruleScores, null);
      
      newRewrittenInputs.add(input);
      final Map msg = telegram_msg();
      
      final NLLogicChecker_v3 c = new NLLogicChecker_v3 {
        bool checkExpression_impl(Exp e, Matching m) {
          if (e instanceof Literal) {
            // TEXT CONDITIONS
            
            S text = nlLogic_text(e);
            if (eq(text, "authorized"))
              ret telegram_amIAuthorized();
            else if(eq(text, "imagineMode"))
              ret imagineMode;
          }
          
          ret super.checkExpression_impl(e, m);
        }
      };

      c.evaluator = func(Exp e, NLLogicChecker_v2.Matching m) -> O { evalExp(c, e, m) };
      
      if (collectCheckingLog) {
        checkingLog = new L;
        nlLogic_collectCheckingLog(c, checkingLog);
      }
      
      Pair<L<IfThen>, LS> rulesAndFacts = getRulesAndFacts();
      c.facts = reversed(rulesAndFacts.b);
      rules = concatLists_conservative(activeTempRules, reversed(rulesAndFacts.a)); // latest rules first!
      activeTempRules.clear();

      while (!posted && now() < cancelTime && nempty(newRewrittenInputs)) {
        fS s = first(newRewrittenInputs);
        rewrittenInputs.add(s);
        newRewrittenInputs.remove(s);
      
        c.input = s;
        c.recentHistory = recentHistory;
        final new L<RuleWithParams> battleSpace;
    
        applyNLLogicFacts_v4_verbose.set(debug);
        applyNLLogicFacts_v4(c, voidfunc(IfThen rule, NLLogicChecker_v2.Matching m) {
          // Rule matches completely, add to battle space
          
          battleSpace.add(new RuleWithParams(rule, m.matches));
        }, rules);
        
        print("Have " + n2(battleSpace, "possible rule")
          + (empty(battleSpace) ? "" : ": " + joinWithComma(map(func(RuleWithParams r) -> S { r.ruleID() + "/" + toInt(ruleScores.get(r.ruleID())) }, battleSpace))));
        
        bool all = options.contains("all");
        if (!all) nlLogic_battleItOut(battleSpace, c.facts);
        
        L<RuleWithParams> winners = all ? battleSpace : nlLogic_highestScore(battleSpace, ruleScores);
    
        fS msgGlobalID = getString(msg, 'globalID);
        //print("msgGlobalID=" + msgGlobalID);
        for (RuleWithParams r : winners) {
          print("Firing rule " + r.rule.globalID);
          
          // Save rule fire
          if (nempty(msgGlobalID) && nempty(r.rule.globalID)) {
            S fact = format("Rule * fired on message * at *", r.rule.globalID, msgGlobalID, localDateWithMilliseconds());
             if (nempty(r.matches))
               fact += " with vars " + dropPrefix("lhm", struct(r.matches));
            print("Saving rule fire. Mech mode: " + mechMode());
            print(addToMechList("Telegram Rule Fires", print(fact)));
          }
          
          executeRule(c, r);
        }
        
        if (collectCheckingLog)
          print("Checking log length: " + l(checkingLog));
      }
    }
    
    void executeRule(NLLogicChecker_v3 c, RuleWithParams r) {
      // Execute rule
      for (Exp e : nlLogic_unrollAnd(r.rule.out)) {
        e = c.apply(e, r.matches);
        if (e cast Func) {
          S name = e.name;
          if (eqOneOf(name, 'output, 'say))
            postMessage(nlLogic_text(e.arg));
          else if (eq(name, 'fact)) {
            S fact = nlLogic_text(e.arg);
            if (imagineMode) {
              if (!containsNL(imaginedFacts, fact)) {
                imaginedFacts.add(fact);
                postMessage("Storing imaginary fact: " + fact);
              }
            } else if (!ai_isQuestion_2(fact) && ai_storeActualFact(fact))
              postMessage("Storing fact: " + fact);
          } else if (eq(name, 'storeRule)) {
            S rule = nlLogic_text(e.arg);
            if (!telegram_authorizedToStoreRule(rule)) continue;
            rule = nlLogic_addGlobalID(rule);
            if (mech_changed(appendToMechList_noUniq("NL Logic Examples", "\n" + rule)))
              postMessage("Rule stored");
          } else if (eq(name, 'imagineMode)) {
            imagineMode = match("true", nlLogic_text(e.arg));
            if (!imagineMode) imaginedFacts.clear();
          } else if (eq(name, 'input)) {
            S x = nlLogic_text(e.arg);
            if (!rewrittenInputs.contains(x) && newRewrittenInputs.add(x))
              print("New rewritten input: " + x);
          } else
            ret with print("Skipping rule with unknown RHS func: " + e.name);
        } else
          ret with print("Skipping rule with unknown RHS element: " + e);
      }
    }
  } // end class Thinking
 
  Pair<L<IfThen>, LS> getRulesAndFacts() { 
    ret ai_activeRulesAndFacts(imagineMode ? asList(imaginedFacts) : null);
  }

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: 435 / 874
Version history: 25 change(s)
Referenced in: #1017807 - Telegram Facts Bot v5 [Dyn Module, with battling rules, old]
#1017947 - BakedFactsBot
#1017968 - Telegram Facts Bot [Include, backup, pre plan]
#1018038 - Telegram Facts Bot [Include v2]