alleswatikvoel/server.py
2017-03-08 11:13:18 +01:00

99 lines
2.8 KiB
Python

import models
import os
import tornado.ioloop
import tornado.web
import colour
import charts
from PIL import Image
import io
models.db.connect()
curpath = os.path.dirname(os.path.abspath(__file__))
tplpath = os.path.join(curpath, "templates");
loader = tornado.template.Loader(tplpath, autoescape=None)
config = {
"port": 8881,
"conn": models.db
}
emotions = [ e for e in models.Emotion.select()]
class MainHandler(tornado.web.RequestHandler):
def get(self):
loader.reset()
html = loader.load('index.html').generate(host=self.request.host, emotions=emotions, ages=models.getAges(), groups=models.Group.select())
self.write(html)
class ThumbHandler(tornado.web.RequestHandler):
def get(self, imgId):
artwork = models.Artwork.select().where(models.Artwork.id == imgId).get()
if artwork is None:
self.send_error(404)
else:
img = Image.open(artwork.filename)
img.thumbnail((200,200))
fp = io.BytesIO()
img.save(fp, "jpeg")
fp.seek(0)
self.set_header("Content-Type","image/jpeg")
self.set_header("Cache-Control","max-age=2592000, public")
self.write(fp.read())
class ColourHandler(tornado.web.RequestHandler):
def get(self):
req_group = self.get_query_argument("group", default=None)
req_age = self.get_query_argument("age", default=None)
req_emotion = self.get_query_argument("emotion", default=None)
q = models.Artwork.select()
if req_group is not None:
group = models.Group.get(models.Group.id == req_group)
q = q.where(models.Artwork.group == group)
elif req_age is not None:
q = q.where(models.Artwork.age == req_age)
elif req_emotion is not None:
emotion = models.Emotion.get(models.Emotion.id == req_emotion)
q = q.where(models.Artwork.emotion == emotion)
images = q
svg = colour.getSvgFromDbImages(images)
imgHtml = "<aside id='works'>";
# for artwork in images:
# imgHtml += "<img src='/thumbs/%s'>" % artwork.id
imgHtml += "</aside>";
statHtml = "<aside id='stats'>";
if not req_emotion:
statHtml += "<h4>Emoties</h4>"
statHtml += charts.createPie(models.getEmotionFractionsFromArtworks(images))
else:
statHtml += "<h4>Leeftijd</h4>"
statHtml += charts.createPie(models.getAgeFractionsFromArtworks(images))
# statHtml += "<h4>Gezichten</h4>"
# statHtml += "Geen gezichten gevonden"
# statHtml += "<h4>Unieke woorden</h4>" # sorted(tf * idf)[:5]
# statHtml += "Geen woorden gebruikt"
# statHtml += "<h4>Meest voorkomende woorden</h4>"
# statHtml += "Geen woorden gevonden"
# TODO: licht/donker
# if not req_group:
statHtml += "</aside>";
self.write("\n".join([svg, imgHtml, statHtml]) )
if __name__ == "__main__":
print("Start server", config)
app = tornado.web.Application([
(r"/", MainHandler),
(r"/colours", ColourHandler),
(r"/thumbs/(\d+)", ThumbHandler),
], debug=True)
app.listen(config['port'])
tornado.ioloop.IOLoop.current().start()