view bin/paintserver @ 1630:2adbc27f77d3

theater config Ignore-this: bb91223d90437a7f1e496f1d542fe8bb
author drewp@bigasterisk.com
date Sat, 10 Jun 2017 02:07:02 +0000
parents 5d2dcae1a7c6
children 6fa4288da8a6
line wrap: on
line source

#!bin/python

from __future__ import division
from run_local import log
import json
from twisted.internet import reactor
from light9.greplin_cyclone import StatsForCyclone
from light9.rdfdb.syncedgraph import SyncedGraph
from light9 import networking, showconfig
from greplin import scales
import optparse, sys, logging
import cyclone.web
from rdflib import URIRef
from light9.rdfdb import clientsession
import light9.paint.solve
from lib.cycloneerr import PrettyErrorHandler
from light9.namespaces import RDF, L9, DEV




class Solve(PrettyErrorHandler, cyclone.web.RequestHandler):
    def post(self):
        painting = json.loads(self.request.body)
        with self.settings.stats.solve.time():
            img = self.settings.solver.draw(painting)
            sample, sampleDist = self.settings.solver.bestMatch(img, device=DEV['aura2'])
            with self.settings.graph.currentState() as g:
                bestPath = g.value(sample, L9['imagePath']).replace(L9[''], '')
            #out = solver.solve(painting)
            #layers = solver.simulationLayers(out)
            
        self.write(json.dumps({
            'bestMatch': {'uri': sample, 'path': bestPath, 'dist': sampleDist},
        #    'layers': layers,
        #    'out': out,
        }))

    def reloadSolver(self):
        reload(light9.paint.solve)
        self.settings.solver = light9.paint.solve.Solver(self.settings.graph)
        self.settings.solver.loadSamples()

class BestMatches(PrettyErrorHandler, cyclone.web.RequestHandler):
    def post(self):
        body = json.loads(self.request.body)
        painting = body['painting']
        devs = [URIRef(d) for d in body['devices']]
        with self.settings.stats.solve.time():
            img = self.settings.solver.draw(painting)
            outSettings = self.settings.solver.bestMatches(img, devs)
            self.write(json.dumps({
                'settings': outSettings.asList()
                }))
        
class App(object):
    def __init__(self, show, session):
        self.show = show
        self.session = session

        self.graph = SyncedGraph(networking.rdfdb.url, "paintServer")
        self.graph.initiallySynced.addCallback(self.launch).addErrback(log.error)
        
        self.stats = scales.collection('/', scales.PmfStat('solve'),
                                       )
       
    def launch(self, *args):

        self.solver = light9.paint.solve.Solver(self.graph, sessions=[
            L9['show/dance2017/capture/aura1/cap1876596'],
            L9['show/dance2017/capture/aura2/cap1876792'],
            L9['show/dance2017/capture/aura3/cap1877057'],
            L9['show/dance2017/capture/aura4/cap1877241'],
            L9['show/dance2017/capture/aura5/cap1877406'],
            L9['show/dance2017/capture/q1/cap1874255'],
            L9['show/dance2017/capture/q2/cap1873665'],
            L9['show/dance2017/capture/q3/cap1876223'],
        ])
        self.solver.loadSamples()
        
        self.cycloneApp = cyclone.web.Application(handlers=[
            (r'/stats', StatsForCyclone),
            (r'/solve', Solve),
            (r'/bestMatches', BestMatches),
        ],
                                                  debug=True,
                                                  graph=self.graph,
                                                  solver=self.solver,
                                                  stats=self.stats)
        reactor.listenTCP(networking.paintServer.port, self.cycloneApp)
        log.info("listening on %s" % networking.paintServer.port)


if __name__ == "__main__":
    parser = optparse.OptionParser()
    parser.add_option('--show',
        help='show URI, like http://light9.bigasterisk.com/show/dance2008',
                      default=showconfig.showUri())
    parser.add_option("-v", "--verbose", action="store_true",
                      help="logging.DEBUG")
    parser.add_option("--twistedlog", action="store_true",
                      help="twisted logging")
    clientsession.add_option(parser)
    (options, args) = parser.parse_args()
    log.setLevel(logging.DEBUG if options.verbose else logging.INFO)

    if not options.show:
        raise ValueError("missing --show http://...")
        
    session = clientsession.getUri('paint', options)

    app = App(URIRef(options.show), session)
    if options.twistedlog:
        from twisted.python import log as twlog
        twlog.startLogging(sys.stderr)
    reactor.run()