diff service/reasoning/reasoning.py @ 1556:d36d3b9ae516

python 3! and some types and cleanups Ignore-this: 3453a547ee745fa83668f36956c835cd darcs-hash:d9bd8e8a584681078c5de1b6e06c894995400f1f
author drewp <drewp@bigasterisk.com>
date Fri, 14 Feb 2020 00:07:23 -0800
parents 606bb60a5e5c
children 3c18b4b3b72c
line wrap: on
line diff
--- a/service/reasoning/reasoning.py	Thu Feb 13 23:00:06 2020 -0800
+++ b/service/reasoning/reasoning.py	Fri Feb 14 00:07:23 2020 -0800
@@ -19,12 +19,15 @@
 
 import json, time, traceback, sys
 from logging import getLogger, DEBUG, WARN
+from typing import Dict, Optional, Set, Tuple
 
 from colorlog import ColoredFormatter
 from docopt import docopt
 from rdflib import Namespace, Literal, RDF, Graph, URIRef
+from rdflib.term import Node
 from twisted.internet import reactor, defer
 import cyclone.web, cyclone.websocket
+from FuXi.Rete.RuleStore import N3RuleStore
 
 from greplin import scales
 from greplin.scales.cyclonehandler import StatsHandler
@@ -48,7 +51,7 @@
                           scales.PmfStat('updateRules'),
 )
 
-def ntStatement(stmt):
+def ntStatement(stmt: Tuple[Node, Node, Node]):
     def compact(u):
         if isinstance(u, URIRef) and u.startswith(ROOM):
             return 'room:' + u[len(ROOM):]
@@ -56,6 +59,7 @@
     return '%s %s %s .' % (compact(stmt[0]), compact(stmt[1]), compact(stmt[2]))
 
 class Reasoning(object):
+    ruleStore: N3RuleStore
     def __init__(self, mockOutput=False):
         self.prevGraph = None
 
@@ -94,7 +98,7 @@
                  Literal(ruleParseTime))], ruleParseTime
 
     @STATS.graphChanged.time()
-    def graphChanged(self, inputGraph, oneShot=False, oneShotGraph=None):
+    def graphChanged(self, inputGraph: InputGraph, oneShot=False, oneShotGraph: Graph = None):
         """
         If we're getting called for a oneShot event, the oneShotGraph
         statements are already in inputGraph.getGraph().
@@ -141,11 +145,11 @@
     def copyOutput(self):
         self.outputGraph.setToGraph((s,p,o,ROOM['inferred']) for s,p,o in self.inferred)
 
-    def _makeInferred(self, inputGraph):
+    def _makeInferred(self, inputGraph: InputGraph):
         t1 = time.time()
 
         out = infer(inputGraph, self.ruleStore)
-        for p, n in NS.iteritems():
+        for p, n in NS.items():
             out.bind(p, n, override=True)
 
         inferenceTime = time.time() - t1
@@ -201,7 +205,7 @@
 
 # for reuse
 class GraphResource(cyclone.web.RequestHandler):
-    def get(self, which):
+    def get(self, which: str):
         self.set_header("Content-Type", "application/json")
         r = self.settings.reasoning
         g = {'lastInput': r.inputGraph.getGraph(),
@@ -242,11 +246,11 @@
         self.finish(msg)
 
 class Static(cyclone.web.RequestHandler):
-    def get(self, p):
+    def get(self, p: str):
         self.write(open(p).read())
 
-liveClients = set()
-def sendToLiveClients(d=None, asJson=None):
+liveClients: Set[cyclone.websocket.WebSocketHandler] = set()
+def sendToLiveClients(d: Dict[str, object]=None, asJson: Optional[str]=None):
     j = asJson or json.dumps(d)
     for c in liveClients:
         c.sendMessage(j)
@@ -274,8 +278,10 @@
             (r'/(jquery.min.js)', Static),
             (r'/(lastInput|lastOutput)Graph', GraphResource),
 
-            (r"/graph/reasoning", CycloneGraphHandler, {'masterGraph': reasoning.outputGraph}),
-            (r"/graph/reasoning/events", CycloneGraphEventsHandler, {'masterGraph': reasoning.outputGraph}),
+            (r"/graph/reasoning", CycloneGraphHandler,
+             {'masterGraph': reasoning.outputGraph}),
+            (r"/graph/reasoning/events", CycloneGraphEventsHandler,
+             {'masterGraph': reasoning.outputGraph}),
 
             (r'/ntGraphs', NtGraphs),
             (r'/rules', Rules),
@@ -289,22 +295,22 @@
     log.setLevel(WARN)
 
     if arg['-i'] or arg['-r'] or arg['-o'] or arg['-v']:
-        log.handlers[0].setFormatter(ColoredFormatter("%(log_color)s%(levelname)-8s %(name)-6s %(filename)-12s:%(lineno)-3s %(funcName)-20s%(reset)s %(white)s%(message)s",
-        datefmt=None,
-        reset=True,
-        log_colors={
+        log.handlers[0].setFormatter(ColoredFormatter(
+            "%(log_color)s%(levelname)-8s %(name)-6s %(filename)-12s:%(lineno)-3s %(funcName)-20s%(reset)s %(white)s%(message)s",
+            datefmt=None,
+            reset=True,
+            log_colors={
                 'DEBUG':    'cyan',
                 'INFO':     'green',
                 'WARNING':  'yellow',
                 'ERROR':    'red',
                 'CRITICAL': 'red,bg_white',
-        },
-        secondary_log_colors={},
-        style='%'
-))
+            },
+            secondary_log_colors={},
+            style='%'
+        ))
         defer.setDebugging(True)
 
-
     if arg['-i']:
         import twisted.python.log
         twisted.python.log.startLogging(sys.stdout)