2019-10-23 08:56:28 +00:00
|
|
|
import logging
|
|
|
|
from sqlalchemy.ext.declarative import declarative_base
|
2019-10-31 13:35:24 +00:00
|
|
|
from sqlalchemy import Column, Integer, String, DateTime, Float
|
2019-10-23 08:56:28 +00:00
|
|
|
from sqlalchemy.orm import relationship
|
|
|
|
from sqlalchemy.sql.schema import ForeignKey, Sequence
|
|
|
|
from sqlalchemy.engine import create_engine
|
|
|
|
from sqlalchemy.orm.session import sessionmaker
|
|
|
|
import datetime
|
|
|
|
from contextlib import contextmanager
|
|
|
|
import uuid
|
|
|
|
import os
|
|
|
|
|
|
|
|
mainLogger = logging.getLogger("sorteerhoed")
|
|
|
|
logger = mainLogger.getChild("store")
|
|
|
|
|
|
|
|
Base = declarative_base()
|
|
|
|
|
|
|
|
"""
|
|
|
|
HIT lifetime:
|
|
|
|
|
|
|
|
|
|
|
|
created
|
|
|
|
accepted
|
|
|
|
(returned!)
|
|
|
|
working
|
|
|
|
awaiting amazon confirmation (submitted on page)
|
|
|
|
submitted
|
|
|
|
|
|
|
|
Actions:
|
|
|
|
creating Hit (creating hit with scanned image)
|
|
|
|
|
2020-01-10 17:03:18 +00:00
|
|
|
Scanning
|
2019-10-23 08:56:28 +00:00
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
class HIT(Base):
|
|
|
|
__tablename__ = 'hits'
|
|
|
|
id = Column(Integer, Sequence('hit_id'), primary_key=True) # our sequential hit id
|
|
|
|
hit_id = Column(String(255)) # amazon's hit id
|
2019-10-30 11:44:25 +00:00
|
|
|
created_at = Column(DateTime, default=datetime.datetime.utcnow)
|
|
|
|
updated_at = Column(DateTime, default=datetime.datetime.utcnow)
|
|
|
|
scanned_at = Column(DateTime, default=None)
|
2020-01-13 12:49:59 +00:00
|
|
|
plotted_at = Column(DateTime, default=None)
|
2020-01-10 17:03:18 +00:00
|
|
|
deleted_at = Column(DateTime, default=None)
|
|
|
|
assignments = relationship("Assignment", back_populates="hit", order_by="Assignment.created_at")
|
2019-10-31 13:35:24 +00:00
|
|
|
fee = Column(Float(precision=2), default=None)
|
2020-01-10 17:03:18 +00:00
|
|
|
|
|
|
|
# previous hit so we can load the corrent image
|
|
|
|
# previous_hit_id = Column(Integer, ForeignKey('hits.id'), default=None)
|
|
|
|
# previous_hit = relationship("HIT")
|
|
|
|
|
2019-10-23 20:33:37 +00:00
|
|
|
def getImagePath(self):
|
2019-12-18 17:49:07 +00:00
|
|
|
return os.path.join('scanimation/interfaces/frames', f"{self.id:06d}.jpg")
|
2020-01-13 12:49:59 +00:00
|
|
|
|
|
|
|
def getImageUrl(self):
|
|
|
|
return os.path.join('/frames', f"{self.id:06d}.jpg")
|
2020-01-10 17:03:18 +00:00
|
|
|
|
2019-11-02 17:09:21 +00:00
|
|
|
def getSvgImageUrl(self):
|
2019-11-02 17:14:05 +00:00
|
|
|
return f"scans/{self.id:06d}.svg"
|
2020-01-10 17:03:18 +00:00
|
|
|
|
2019-11-02 19:45:57 +00:00
|
|
|
def getSvgImagePath(self):
|
|
|
|
return os.path.join('www', self.getSvgImageUrl())
|
2019-10-23 08:56:28 +00:00
|
|
|
|
2020-01-10 17:03:18 +00:00
|
|
|
def getLastAssignment(self):
|
|
|
|
if not len(self.assignments):
|
|
|
|
return None
|
|
|
|
return self.assignments[-1]
|
|
|
|
|
|
|
|
def getAssignmentById(self, assignmentId):
|
|
|
|
for a in self.assignments:
|
|
|
|
if a.assignment_id == assignmentId:
|
2020-01-13 12:49:59 +00:00
|
|
|
return a
|
|
|
|
return None
|
2020-01-10 17:03:18 +00:00
|
|
|
|
2019-10-30 11:44:25 +00:00
|
|
|
def getStatus(self):
|
2020-01-13 12:49:59 +00:00
|
|
|
assignment = self.getLastAssignment()
|
|
|
|
if self.deleted_at:
|
|
|
|
return "deleted"
|
|
|
|
if not self.hit_id:
|
|
|
|
return "creating"
|
|
|
|
if not assignment:
|
|
|
|
return "awaiting worker"
|
2019-10-30 11:44:25 +00:00
|
|
|
if self.scanned_at:
|
2020-01-13 12:49:59 +00:00
|
|
|
return "scanned"
|
|
|
|
return assignment.getStatus()
|
|
|
|
|
|
|
|
def toDict(self) -> dict:
|
|
|
|
values = {c.name: getattr(self, c.name) for c in self.__table__.columns}
|
|
|
|
assignment = self.getLastAssignment()
|
|
|
|
values['assignment'] = assignment.toDict() if assignment else None
|
|
|
|
values['state'] = self.getStatus()
|
|
|
|
values['scan_image'] = self.getImageUrl() if self.scanned_at else None
|
|
|
|
values['svg_image'] = self.getSvgImageUrl() if self.isSubmitted() else None
|
|
|
|
return values
|
|
|
|
|
|
|
|
def delete(self):
|
|
|
|
self.deleted_at = datetime.datetime.utcnow()
|
|
|
|
|
|
|
|
def isSubmitted(self) -> bool:
|
|
|
|
a = self.getLastAssignment()
|
|
|
|
if not a:
|
|
|
|
return False
|
|
|
|
return bool(a.submit_page_at)
|
|
|
|
|
|
|
|
def isConfirmed(self) -> bool:
|
|
|
|
a = self.getLastAssignment()
|
|
|
|
if not a:
|
|
|
|
return False
|
|
|
|
return bool(a.confirmed_at)
|
2019-10-30 11:44:25 +00:00
|
|
|
|
2020-01-10 17:03:18 +00:00
|
|
|
class Assignment(Base):
|
|
|
|
__tablename__ = 'assignments'
|
|
|
|
id = Column(Integer, Sequence('assignment_id'), primary_key=True) # our sequential hit id
|
|
|
|
assignment_id = Column(String(255)) # amazon's assignment id
|
|
|
|
hit_id = Column(Integer, ForeignKey('hits.id')) # our sequential hit id
|
|
|
|
hit = relationship("HIT", back_populates="assignments")
|
|
|
|
uuid = Column(String(32), default=lambda : uuid.uuid4().hex)
|
|
|
|
|
|
|
|
created_at = Column(DateTime, default=datetime.datetime.utcnow)
|
|
|
|
updated_at = Column(DateTime, default=datetime.datetime.utcnow)
|
|
|
|
|
|
|
|
assignment_id = Column(String(255), default = None)
|
|
|
|
worker_id = Column(String(255), default = None)
|
2020-01-13 12:49:59 +00:00
|
|
|
accept_at = Column(DateTime, default=None) # accept time acccording to SQS
|
2020-01-10 17:03:18 +00:00
|
|
|
# open_page_at = Column(DateTime, default=None)
|
|
|
|
submit_page_at = Column(DateTime, default=None) # Submit the page
|
|
|
|
confirmed_at = Column(DateTime, default=None) # validate with UUID when getting Message from Amazon
|
|
|
|
abandoned_at = Column(DateTime, default=None)
|
|
|
|
rejected_at = Column(DateTime, default=None)
|
|
|
|
|
|
|
|
answer = Column(String(255), default=None)
|
|
|
|
turk_ip = Column(String(255), default=None)
|
|
|
|
turk_country = Column(String(255), default=None)
|
2020-01-13 12:49:59 +00:00
|
|
|
turk_os = Column(String(255), default=None)
|
|
|
|
turk_browser = Column(String(255), default=None)
|
|
|
|
|
|
|
|
def getStatus(self):
|
|
|
|
if self.rejected_at:
|
|
|
|
return "rejected"
|
|
|
|
if self.abandoned_at:
|
|
|
|
return "abandoned"
|
|
|
|
if not self.submit_page_at:
|
|
|
|
return "working"
|
|
|
|
if not self.confirmed_at:
|
|
|
|
return "submitted"
|
|
|
|
return "confirmed"
|
|
|
|
|
|
|
|
def toDict(self) -> dict:
|
|
|
|
values = {c.name: getattr(self, c.name) for c in self.__table__.columns}
|
|
|
|
return values
|
|
|
|
|
2019-10-23 08:56:28 +00:00
|
|
|
|
|
|
|
class Store:
|
|
|
|
def __init__(self, db_filename, logLevel=0):
|
|
|
|
path = os.path.abspath(db_filename)
|
|
|
|
if logLevel <= logging.DEBUG:
|
|
|
|
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
|
2020-01-10 17:03:18 +00:00
|
|
|
|
2019-10-23 20:33:37 +00:00
|
|
|
self.engine = create_engine('sqlite:///'+path, echo=False, connect_args={'check_same_thread': False})
|
2019-10-23 08:56:28 +00:00
|
|
|
Base.metadata.create_all(self.engine)
|
|
|
|
self.Session = sessionmaker(bind=self.engine)
|
2019-10-23 20:33:37 +00:00
|
|
|
self.session = self.Session()
|
2020-01-10 17:03:18 +00:00
|
|
|
|
2019-11-01 16:02:38 +00:00
|
|
|
self.currentHit = None # mirrors Centralmanagmenet, stored here so we can quickly access it from webserver classes
|
2020-01-13 12:49:59 +00:00
|
|
|
self.updateHooks = []
|
|
|
|
|
|
|
|
def registerUpdateHook(self, hook):
|
|
|
|
if hook not in self.updateHooks:
|
|
|
|
logger.info(f"Register update hook: {hook}")
|
|
|
|
self.updateHooks.append(hook)
|
|
|
|
|
|
|
|
def triggerUpdateHooks(self, hit = None):
|
|
|
|
for hook in self.updateHooks:
|
|
|
|
if callable(hook): # it's a method
|
|
|
|
hook(hit)
|
|
|
|
else: # assume it's an object
|
|
|
|
hook.update(hit)
|
2020-01-10 17:03:18 +00:00
|
|
|
|
2019-10-23 08:56:28 +00:00
|
|
|
@contextmanager
|
|
|
|
def getSession(self):
|
|
|
|
"""Provide a transactional scope around a series of operations."""
|
|
|
|
try:
|
2019-10-23 20:33:37 +00:00
|
|
|
yield self.session
|
|
|
|
self.session.commit()
|
2019-10-23 08:56:28 +00:00
|
|
|
except:
|
2019-10-23 20:33:37 +00:00
|
|
|
self.session.rollback()
|
2019-10-23 08:56:28 +00:00
|
|
|
raise
|
2020-01-10 17:03:18 +00:00
|
|
|
|
2020-01-13 12:49:59 +00:00
|
|
|
def getHits(self):
|
|
|
|
return self.session.query(HIT).order_by(HIT.created_at.desc())
|
2020-01-10 17:03:18 +00:00
|
|
|
|
2019-10-23 20:33:37 +00:00
|
|
|
def getHitById(self, hitId):
|
|
|
|
return self.session.query(HIT).\
|
|
|
|
filter(HIT.id==hitId).one()
|
2020-01-10 17:03:18 +00:00
|
|
|
|
2019-10-23 20:33:37 +00:00
|
|
|
def getHitByRemoteId(self, amazonHitId):
|
|
|
|
return self.session.query(HIT).\
|
|
|
|
filter(HIT.hit_id==amazonHitId).one()
|
2020-01-10 17:03:18 +00:00
|
|
|
|
|
|
|
|
2019-10-23 20:33:37 +00:00
|
|
|
def getLastSubmittedHit(self):
|
|
|
|
return self.session.query(HIT).\
|
2020-01-13 12:49:59 +00:00
|
|
|
join(Assignment).\
|
|
|
|
filter(Assignment.submit_page_at!=None).\
|
|
|
|
order_by(HIT.created_at.desc()).first()
|
|
|
|
|
|
|
|
def getNewestHits(self, n = 2) -> list:
|
|
|
|
hits = list(
|
|
|
|
self.session.query(HIT).\
|
|
|
|
filter(HIT.deleted_at==None).\
|
|
|
|
order_by(HIT.created_at.desc()).limit(2)
|
|
|
|
)
|
|
|
|
# select DESC, because we want latest, then reverse list to get in right order
|
|
|
|
hits.reverse()
|
|
|
|
return hits
|
2020-01-10 17:03:18 +00:00
|
|
|
|
|
|
|
def createHIT(self) -> HIT:
|
2019-10-23 20:33:37 +00:00
|
|
|
with self.getSession() as s:
|
|
|
|
hit = HIT()
|
|
|
|
s.add(hit)
|
|
|
|
s.flush()
|
|
|
|
s.refresh(hit)
|
|
|
|
logger.info(f"Created HIT {hit.id}")
|
2020-01-13 12:49:59 +00:00
|
|
|
|
|
|
|
self.triggerUpdateHooks(hit)
|
|
|
|
|
2019-10-23 20:33:37 +00:00
|
|
|
return hit
|
2020-01-10 17:03:18 +00:00
|
|
|
|
2020-01-13 12:49:59 +00:00
|
|
|
def newAssignment(self, hit: HIT, assignmentId) -> Assignment:
|
|
|
|
# TODO: reset() central management if has pending lastAssignment()
|
|
|
|
|
2020-01-10 17:03:18 +00:00
|
|
|
with self.getSession() as s:
|
|
|
|
assignment = Assignment()
|
2020-01-13 12:49:59 +00:00
|
|
|
assignment.assignment_id = assignmentId
|
2020-01-10 17:03:18 +00:00
|
|
|
hit.assignments.append(assignment)
|
|
|
|
s.add(assignment)
|
|
|
|
s.flush()
|
|
|
|
s.refresh(hit)
|
|
|
|
logger.info(f"Created Assignment {assignment.id}")
|
2020-01-13 12:49:59 +00:00
|
|
|
|
|
|
|
self.triggerUpdateHooks(hit)
|
|
|
|
|
2020-01-10 17:03:18 +00:00
|
|
|
return assignment
|
|
|
|
|
2019-10-23 20:33:37 +00:00
|
|
|
def saveHIT(self, hit):
|
|
|
|
with self.getSession() as s:
|
|
|
|
logger.info(f"Updating hit! {hit.id}")
|
|
|
|
# s.flush()
|
2020-01-13 12:49:59 +00:00
|
|
|
self.triggerUpdateHooks(hit)
|
2020-01-10 17:03:18 +00:00
|
|
|
|
2020-01-13 12:49:59 +00:00
|
|
|
def saveAssignment(self, assignment):
|
2019-10-23 08:56:28 +00:00
|
|
|
with self.getSession() as s:
|
2020-01-13 12:49:59 +00:00
|
|
|
logger.info(f"Updating assignment! {assignment.id}")
|
|
|
|
# s.flush()
|
|
|
|
self.triggerUpdateHooks(assignment.hit)
|
|
|
|
|
|
|
|
# def addHIT(self, hit: HIT):
|
|
|
|
# with self.getSession() as s:
|
|
|
|
# s.add(hit)
|
|
|
|
# s.flush()
|
|
|
|
# s.refresh(hit)
|
|
|
|
# logger.info(f"Added {hit.id}")
|
2020-01-10 17:03:18 +00:00
|
|
|
|
2019-10-30 11:44:25 +00:00
|
|
|
def getAvgDurationOfPreviousNHits(self, n) -> int:
|
2020-01-13 12:49:59 +00:00
|
|
|
latest_assignments = self.session.query(Assignment).\
|
|
|
|
filter(Assignment.created_at!=None).\
|
|
|
|
filter(Assignment.submit_page_at!=None).\
|
|
|
|
order_by(Assignment.created_at.desc()).limit(n)
|
2019-10-30 11:44:25 +00:00
|
|
|
durations = []
|
2020-01-13 12:49:59 +00:00
|
|
|
|
|
|
|
for assignment in latest_assignments:
|
|
|
|
durations.append((assignment.submit_page_at - assignment.created_at).total_seconds())
|
2019-10-30 11:44:25 +00:00
|
|
|
if not len(durations):
|
2020-01-13 12:49:59 +00:00
|
|
|
return int(2.5*60) # default to 2.5 minutes
|
2019-10-30 11:44:25 +00:00
|
|
|
return int(sum(durations) / len(durations))
|
2020-01-10 17:03:18 +00:00
|
|
|
|
2019-11-02 19:45:57 +00:00
|
|
|
def getEstimatedHitDuration(self):
|
|
|
|
return self.getAvgDurationOfPreviousNHits(5)
|
2020-01-10 17:03:18 +00:00
|
|
|
|
2019-11-02 21:31:16 +00:00
|
|
|
def getHitTimeout(self):
|
2019-11-04 09:48:05 +00:00
|
|
|
return 160 # max(160, self.getAvgDurationOfPreviousNHits(5)*2)
|
2020-01-10 17:03:18 +00:00
|
|
|
|
2019-10-31 13:35:24 +00:00
|
|
|
def getHITs(self, n = 100):
|
|
|
|
return self.session.query(HIT).\
|
|
|
|
filter(HIT.submit_hit_at != None).\
|
|
|
|
order_by(HIT.submit_hit_at.desc()).limit(n)
|