Example #1
0
def Main():
    d1 = datetime.datetime.now()
    
    lonelyMan = RenRenSpider()
    lonelyMan.login()
    userID = lonelyMan.getUserID()
    
    checkPaths(userID)
    checkPaths(ownerID=config.ownerID)
 
    albumList = AlbumList(userID,lonelyMan,ownerID=config.ownerID)
    albumList.work()
       
    status = Status(userID,lonelyMan,config.ownerID)
    status.work()
 
    bloglist = BlogList(userID,lonelyMan,config.ownerID)
    bloglist.work()
   
    gossip = Gossip(userID,lonelyMan,config.ownerID)
    gossip.work()
        
    repo = RepoMysql(userID,lonelyMan)
    repo.work()
    
    d2 = datetime.datetime.now()
    print 'all have been done, time: ', d2 - d1
Example #2
0
    def __init__(self, *args):

        Status.__init__(self, *args) 
 
        # init client server params...
        CliServerParams(self)       

        return
def getPosts(user,clean=True,maxPosts=100):
    try:
        userName = user.facebookId
        args = {}

        graph = GraphAPI(at)
        profile = graph.get_object(userName)
        posts = graph.get_connections(profile['id'], 'posts', **args)
        statuses = []
        lastUntil = ''
    
        for s in posts['paging']['next'].split('&'):
            if 'limit=' in s:
                args['limit'] = s.split('=')[1]
            if 'until=' in s:
                args['until'] = s.split('=')[1]
        while True:
            isBreak = False
            for data in posts['data']:
                if 'message' not in data:
                    continue
                smessage = str(data['message'].encode("utf-8")).replace('\\n', ' ').replace('\\r', '')[2:-1]
                if clean:
                    smessage = re.sub(r'https?:\/\/[^\s]*','',smessage, flags=re.MULTILINE)
                    smessage = re.sub(r'\\x..','',smessage, flags=re.MULTILINE)
                    smessage = re.sub(r'&','and',smessage, flags=re.IGNORECASE)
                    smessage = re.sub(r'[\s\t]+',' ',smessage, flags=re.IGNORECASE)
                    smessage.replace('#','')

                if validPost(smessage):
                    st = Status()
                    st.statusText = smessage
                    st.id = data['id']
                    statuses.append(st)

            if len(statuses) > maxPosts:
                break
            posts = graph.get_connections(profile['id'], 'posts',**args)
            nargs = {}
            for s in posts['paging']['next'].split('&'):
                if 'limit=' in s:
                    nargs['limit'] = s.split('=')[1]
                if 'until=' in s:
                    nargs['until'] = s.split('=')[1]
            if nargs['until'] == args['until']:
                break
            else:
                args['limit'] = nargs['limit']
                args['until'] = nargs['until']
        return statuses
    except ConnectionError:
        return []
Example #4
0
class Cleaner(Actor):
    def __init__(self, cfg_params):
        """
        constructor
        """
        self.status = Status(cfg_params)

    def check(self):
        """
        Check whether no job is still running or not yet retrieved
        """

        task = common._db.getTask()
        upTask = common.scheduler.queryEverything(task['id'])
        self.status.compute(upTask) # compute the status

        jobTerm=[]
        jobSub=[]
        for job  in task.jobs:
            st=job.runningJob['state']
            if st not in ['KillSuccess', 'SubFailed', 'Created', 'Aborted', 'Cleared', 'Cleaned']:
                if st in ['Terminated']: jobTerm.append(job['jobId'])
                if st in ['SubSuccess']: jobSub.append(job['jobId'])
            pass

        if len(jobTerm)>0 or len(jobSub)>0:
            msg = "There are still "
            if len(jobSub)>0:
                msg= msg+" jobs submitted. Kill them '-kill %s' before '-clean'"%readableList(self,jobSub)
            if (len(jobTerm)>0 or len(jobSub)>0):
                msg = msg + "and \nalso"
            if len(jobTerm)>0:
                msg= msg+" jobs Done. Get their outputs '-get %s' before '-clean'"%readableList(self,jobTerm)
            raise CrabException(msg)
        pass

    def run(self):
        """
        remove all
        """
        if common._db.nJobs()>0:
            self.check()

        # here I should first purge boss DB if central
        #common.scheduler.clean()
        common.work_space.delete()
        print 'directory '+common.work_space.topDir()+' removed'
Example #5
0
class Cell(object):
    def __init__(self, position=None):
        self.status = Status()
        self.position = position

    def is_mine(self):
        return False

    def __str__(self):
        return self.status.__str__()
Example #6
0
 def __init__(self, cfg_params):
     """
     constructor
     """
     self.status = Status(cfg_params)
Example #7
0
    def __init__(
        self,
        torrentIdent,
        globalStatus,
        connStatsCache,
        connStatus,
        remotePeerId,
        scheduler,
        conn,
        direction,
        remotePeerAddr,
        inMeasureParent,
        outMeasureParent,
        outLimiter,
        inLimiter,
    ):

        log = Logger("BtConnection", "%-6s - %-6s - ", torrentIdent, conn.fileno())
        inRate, outRate = connStatsCache.get(torrentIdent, remotePeerAddr, remotePeerId)

        Connection.__init__(
            self,
            connStatus,
            scheduler,
            conn,
            direction,
            remotePeerAddr,
            inRate,
            outRate,
            inMeasureParent,
            outMeasureParent,
            outLimiter,
            inLimiter,
            Messages.getMessageLength,
            Messages.decodeMessage,
            4,
            140000,
            Messages.generateKeepAlive,
            log,
        )

        # ident
        self.torrentIdent = torrentIdent

        # peer
        self.remotePeerId = remotePeerId
        self.remoteClient = peerIdToClient(remotePeerId)

        # conn stats cache
        self.connStatsCache = connStatsCache

        # piece status
        self.status = Status(globalStatus.getPieceAmount(), globalStatus)

        # choke and interest state
        self.localInterest = False
        self.remoteInterest = False
        self.localChoke = True
        self.remoteChoke = True

        # requests
        self.outRequestsInFlight = 0
        self.outRequestQueue = []
        self.outRequestHandles = {}
        self.maxInRequests = self._calculateMaxAmountOfInRequests()
        self.inRequestQueue = []
        self.inRequestInfo = {}

        # events
        self.requestTimeoutEvent = None
Example #8
0
class BtConnection(Connection):
    def __init__(
        self,
        torrentIdent,
        globalStatus,
        connStatsCache,
        connStatus,
        remotePeerId,
        scheduler,
        conn,
        direction,
        remotePeerAddr,
        inMeasureParent,
        outMeasureParent,
        outLimiter,
        inLimiter,
    ):

        log = Logger("BtConnection", "%-6s - %-6s - ", torrentIdent, conn.fileno())
        inRate, outRate = connStatsCache.get(torrentIdent, remotePeerAddr, remotePeerId)

        Connection.__init__(
            self,
            connStatus,
            scheduler,
            conn,
            direction,
            remotePeerAddr,
            inRate,
            outRate,
            inMeasureParent,
            outMeasureParent,
            outLimiter,
            inLimiter,
            Messages.getMessageLength,
            Messages.decodeMessage,
            4,
            140000,
            Messages.generateKeepAlive,
            log,
        )

        # ident
        self.torrentIdent = torrentIdent

        # peer
        self.remotePeerId = remotePeerId
        self.remoteClient = peerIdToClient(remotePeerId)

        # conn stats cache
        self.connStatsCache = connStatsCache

        # piece status
        self.status = Status(globalStatus.getPieceAmount(), globalStatus)

        # choke and interest state
        self.localInterest = False
        self.remoteInterest = False
        self.localChoke = True
        self.remoteChoke = True

        # requests
        self.outRequestsInFlight = 0
        self.outRequestQueue = []
        self.outRequestHandles = {}
        self.maxInRequests = self._calculateMaxAmountOfInRequests()
        self.inRequestQueue = []
        self.inRequestInfo = {}

        # events
        self.requestTimeoutEvent = None

    ##internal functions - socket

    def _gotMessage(self, msg):
        if msg[0] == 7:
            # a piece part
            if self._hasThisInRequest(msg[1][0], msg[1][1], len(msg[1][2])):
                # a valid one even
                assert self.requestTimeoutEvent is not None, "got data for a request but no request timeout exists?!"
                if self._amountOfInRequests() == 1:
                    self.sched.removeEvent(self.requestTimeoutEvent)
                    self.requestTimeoutEvent = None
                else:
                    self.sched.rescheduleEvent(self.requestTimeoutEvent, timedelta=120)
                self.inRate.updatePayloadCounter(len(msg[1][2]))

    def _close(self):
        Connection._close(self)

        # store inRate and outRate
        self.connStatsCache.store(self.torrentIdent, self.remotePeerAddr, self.remotePeerId, self.inRate, self.outRate)

        # clear piece status
        self.status.clear()

        # set interest and choke states to defaults
        self.localInterest = False
        self.remoteInterest = False
        self.localChoke = True
        self.remoteChoke = True

        # remove requests
        self._delAllOutRequests()
        self._delAllInRequests()

    ##internal functions - inrequests

    def _addInRequest(self, pieceIndex, offset, length, callback=None, callbackArgs=[], callbackKw={}):
        assert self.remoteChoke == False, "requesting but choked?!"

        # add timeout
        if self.requestTimeoutEvent is None:
            self.requestTimeoutEvent = self.sched.scheduleEvent(
                self.timeout, timedelta=120, funcArgs=["request timed out"]
            )

        # add request
        messageId = self._queueSend(Messages.generateRequest(pieceIndex, offset, length))
        inRequest = (pieceIndex, offset, length)
        assert not inRequest in self.inRequestInfo, "queueing an already queued request?!"
        self.inRequestQueue.append(inRequest)
        self.inRequestInfo[inRequest] = {
            "messageId": messageId,
            "func": callback,
            "funcArgs": callbackArgs,
            "funcKw": callbackKw,
        }

    def _getInRequestsOfPiece(self, pieceIndex):
        requests = set([inRequest[1] for inRequest in self.inRequestQueue if inRequest[0] == pieceIndex])
        return requests

    def _finishedInRequest(self, pieceIndex, offset, length):
        # try to find the request and delete it if found
        inRequest = (pieceIndex, offset, length)
        self.inRequestQueue.remove(inRequest)
        del self.inRequestInfo[inRequest]

    def _cancelInRequest(self, pieceIndex, offset, length):
        # try to find the request, send cancel and then delete it
        inRequest = (pieceIndex, offset, length)
        self.inRequestQueue.remove(inRequest)
        requestInfo = self.inRequestInfo.pop(inRequest)
        if not self._abortSend(requestInfo["messageId"]):
            # the request was already send
            self._queueSend(Messages.generateCancel(pieceIndex, offset, length))

    def _delAllInRequests(self):
        for requestInfo in self.inRequestInfo.itervalues():
            # call callback of failed request
            self._abortSend(requestInfo["messageId"])
            if requestInfo["func"] is not None:
                apply(requestInfo["func"], requestInfo["funcArgs"], requestInfo["funcKw"])
        self.inRequestQueue = []
        self.inRequestInfo = {}

    def _hasThisInRequest(self, pieceIndex, offset, length):
        return (pieceIndex, offset, length) in self.inRequestInfo

    def _amountOfInRequests(self):
        return len(self.inRequestQueue)

    def _calculateMaxAmountOfInRequests(self):
        if self.remoteClient.startswith("Azureus"):
            limit = 16

        elif self.remoteClient.startswith("I2PRufus"):
            limit = 16

        elif self.remoteClient.startswith("I2PSnark"):
            limit = 32

        elif self.remoteClient.startswith("PyBit") and " " in self.remoteClient:
            version = tuple((int(digit) for digit in self.remoteClient.split(" ")[1].split(".")))
            if version < (0, 0, 9):
                limit = 32
            else:
                limit = 64

        elif self.remoteClient.startswith("Robert"):
            limit = 31

        else:
            # I2P-Bt and unknown
            limit = 16

        return limit

    def _getMaxAmountOfInRequests(self):
        return self.maxInRequests

    ##internal functions - outrequests

    def _sendOutRequest(self):
        # queue one outrequest in the outbuffer
        outRequest = self.outRequestQueue.pop(0)
        try:
            # try to get data
            data = self.outRequestHandles.pop(outRequest)()
        except StorageException:
            # failed to get data
            self.log.error("Failed to get data for outrequest:\n%s", logTraceback())
            data = None
            self._fail("could not get data for outrequest")

        if data is not None:
            # got data
            if not len(data) == outRequest[2]:
                self.log.error("Did not get enough data for outrequest: expected %i, got %i!", outRequest[2], len(data))
                self._fail("could not get data for outrequest")
            else:
                message = Messages.generatePiece(outRequest[0], outRequest[1], data)
                self.outRequestsInFlight += 1
                self._queueSend(message, self._outRequestGotSend, [outRequest[2]])

    def _outRequestGotSend(self, dataSize):
        self.outRate.updatePayloadCounter(dataSize)
        self.outRequestsInFlight -= 1
        assert self.outRequestsInFlight == 0, "multiple out requests in flight?!"
        assert len(self.outRequestQueue) == len(
            self.outRequestHandles
        ), "out of sync: queue length %i but %i handles!" % (len(self.outRequestQueue), len(self.outRequestHandles))
        if len(self.outRequestQueue) > 0 and self.outRequestsInFlight == 0:
            self._sendOutRequest()

    def _addOutRequest(self, pieceIndex, offset, length, dataHandle):
        self.outRequestQueue.append((pieceIndex, offset, length))
        self.outRequestHandles[(pieceIndex, offset, length)] = dataHandle
        if self.outRequestsInFlight == 0:
            # no outrequest is currently being send, send one directly
            self._sendOutRequest()

    def _hasThisOutRequest(self, pieceIndex, offset, length):
        return (pieceIndex, offset, length) in self.outRequestHandles

    def _getAmountOfOutRequests(self):
        return len(self.outRequestQueue)

    def _delOutRequest(self, pieceIndex, offset, length):
        # try to find the request and delete it if found
        outRequest = (pieceIndex, offset, length)
        if outRequest in self.outRequestHandles:
            self.outRequestQueue.remove(outRequest)
            del self.outRequestHandles[outRequest]

    def _delAllOutRequests(self):
        self.outRequestQueue = []
        self.outRequestHandles.clear()

    ##internal functions - choking and interest

    def _setLocalInterest(self, value):
        if value == False and self.localInterest == True:
            # changing to negative, we were interested before
            assert self._amountOfInRequests() == 0, "Local Requests are running and we are not interested?"
            # self._cancelAllInRequests()
            self._queueSend(Messages.generateNotInterested())
            self.localInterest = value
        elif value == True and self.localInterest == False:
            self._queueSend(Messages.generateInterested())
            self.localInterest = value

    def _setRemoteInterest(self, value):
        if value == False and self.remoteInterest == True:
            self.setLocalChoke(True)
            self.remoteInterest = value

        elif value == True and self.remoteInterest == False:
            self.remoteInterest = value

    def _setLocalChoke(self, value):
        if value == True and self.localChoke == False:
            # choking
            self._delAllOutRequests()
            self._queueSend(Messages.generateChoke())
            self.localChoke = value

        elif value == False and self.localChoke == True:
            self._queueSend(Messages.generateUnChoke())
            self.localChoke = value

    def _setRemoteChoke(self, value):
        if value == True and self.remoteChoke == False:
            # choked us, delete all incomming requests
            self._delAllInRequests()
            self.remoteChoke = value

        elif value == False and self.remoteChoke == True:
            self.remoteChoke = value

    ##internal functions - other

    def _getScore(self):
        ratio = self._getPayloadRatio()
        score = ratio + (ratio * self.inRate.getAveragePayloadRate())
        return score

    ##external functions - choking and interested

    def localChoked(self):
        self.lock.acquire()
        value = self.localChoke
        self.lock.release()
        return value

    def remoteChoked(self):
        self.lock.acquire()
        value = self.remoteChoke
        self.lock.release()
        return value

    def localInterested(self):
        self.lock.acquire()
        value = self.localInterest
        self.lock.release()
        return value

    def remoteInterested(self):
        self.lock.acquire()
        value = self.remoteInterest
        self.lock.release()
        return value

    def setLocalInterest(self, value):
        self.lock.acquire()
        if not self.closed:
            self._setLocalInterest(value)
        self.lock.release()

    def setRemoteInterest(self, value):
        self.lock.acquire()
        if not self.closed:
            self._setRemoteInterest(value)
        self.lock.release()

    def setLocalChoke(self, value):
        self.lock.acquire()
        if not self.closed:
            self._setLocalChoke(value)
        self.lock.release()

    def setRemoteChoke(self, value):
        self.lock.acquire()
        if not self.closed:
            self._setRemoteChoke(value)
        self.lock.release()

    ##external functions - inrequests

    def addInRequest(self, pieceIndex, offset, length, failFunc=None, failFuncArgs=[], failFuncKw={}):
        self.lock.acquire()
        assert not self.remoteChoke, "uhm, we are not allowed to make requests?!"
        if not self.closed:
            self._addInRequest(pieceIndex, offset, length, failFunc, failFuncArgs, failFuncKw)
        self.lock.release()

    def getInRequestsOfPiece(self, pieceIndex):
        self.lock.acquire()
        requests = self._getInRequestsOfPiece(pieceIndex)
        self.lock.release()
        return requests

    def finishedInRequest(self, pieceIndex, offset, length):
        self.lock.acquire()
        if not self.closed:
            self._finishedInRequest(pieceIndex, offset, length)
        self.lock.release()

    def cancelInRequest(self, pieceIndex, offset, length):
        self.lock.acquire()
        if not self.closed:
            self._cancelInRequest(pieceIndex, offset, length)
        self.lock.release()

    def hasThisInRequest(self, pieceIndex, offset, length):
        self.lock.acquire()
        value = self._hasThisInRequest(pieceIndex, offset, length)
        self.lock.release()
        return value

    def getAmountOfInRequests(self):
        self.lock.acquire()
        value = self._amountOfInRequests()
        self.lock.release()
        return value

    def getMaxAmountOfInRequests(self):
        self.lock.acquire()
        value = self._getMaxAmountOfInRequests()
        self.lock.release()
        return value

    ##internal functions - outrequests

    def addOutRequest(self, pieceIndex, offset, length, dataHandle):
        self.lock.acquire()
        if not self.closed:
            self._addOutRequest(pieceIndex, offset, length, dataHandle)
        self.lock.release()

    def hasThisOutRequest(self, pieceIndex, offset, length):
        self.lock.acquire()
        value = self._hasThisOutRequest(pieceIndex, offset, length)
        self.lock.release()
        return value

    def delOutRequest(self, pieceIndex, offset, length):
        self.lock.acquire()
        self._delOutRequest(pieceIndex, offset, length)
        self.lock.release()

    def getAmountOfOutRequests(self):
        self.lock.acquire()
        value = self._getAmountOfOutRequests()
        self.lock.release()
        return value

    ##external functions - get info

    def getStatus(self):
        self.lock.acquire()
        obj = self.status
        self.lock.release()
        return obj

    def getScore(self):
        self.lock.acquire()
        score = self._getScore()
        self.lock.release()
        return score

    def getRemotePeerId(self):
        self.lock.acquire()
        value = self.remotePeerId
        self.lock.release()
        return value

    def getTorrentIdent(self):
        self.lock.acquire()
        value = self.torrentIdent
        self.lock.release()
        return value

    ##external functions - stats

    def getStats(self):
        self.lock.acquire()
        stats = {}
        stats["id"] = self.connIdent
        stats["addr"] = self.conn.getpeername()
        stats["direction"] = self.direction
        stats["connectedInterval"] = time() - self.connectTime
        stats["totalConnectedInterval"] = self.inRate.getTotalRunTime()
        stats["peerProgress"] = self.status.getPercent()
        stats["peerClient"] = self.remoteClient
        stats["inRawBytes"] = self.inRate.getTotalTransferedBytes()
        stats["outRawBytes"] = self.outRate.getTotalTransferedBytes()
        stats["inPayloadBytes"] = self.inRate.getTotalTransferedPayloadBytes()
        stats["outPayloadBytes"] = self.outRate.getTotalTransferedPayloadBytes()
        stats["inRawSpeed"] = self.inRate.getCurrentRate()
        stats["outRawSpeed"] = self.outRate.getCurrentRate()
        stats["localInterest"] = self.localInterest
        stats["remoteInterest"] = self.remoteInterest
        stats["localChoke"] = self.localChoke
        stats["remoteChoke"] = self.remoteChoke
        stats["localRequestCount"] = len(self.inRequestQueue)
        stats["remoteRequestCount"] = self.outRequestsInFlight + len(self.outRequestQueue)
        stats["avgInRawSpeed"] = self.inRate.getAverageRate() * 1024
        stats["avgOutRawSpeed"] = self.outRate.getAverageRate() * 1024
        stats["avgInPayloadSpeed"] = self.inRate.getAveragePayloadRate() * 1024
        stats["avgOutPayloadSpeed"] = self.outRate.getAveragePayloadRate() * 1024
        stats["score"] = self._getScore()
        stats["payloadRatio"] = self._getPayloadRatio()
        stats["protocolOverhead"] = (
            100.0 * (stats["inRawBytes"] + stats["outRawBytes"] - stats["inPayloadBytes"] - stats["outPayloadBytes"])
        ) / max(stats["inPayloadBytes"] + stats["outPayloadBytes"], 1.0)
        self.lock.release()
        return stats
Example #9
0
def run_detector():
    # import os
    # os.environ['SDL_VIDEODRIVER'] = 'windib'
    # os.environ['SDL_VIDEODRIVER'] = 'directx'


    parser = OptionParser(usage="""\
    Detect SnapMyinfo QRcodes in a live video stream

    Usage: %prog [options] camera_index
    """)

    parser.add_option('-f','--fs','--fullscreen',
                      dest="fullscreen", default=False,
                      action='store_true',
                      help="""Run the Live Decoder full screen.""")

    parser.add_option('--hw','--hw_accel',
                    dest="hw_accel", default=False,
                    action='store_true',
                    help="""Runs pygame with the directx hw driver (if avail). Automatically assumes fullscreen.""")

    parser.add_option('-s','--scale',
                    dest="scale", default=4.0,
                    action='store', type="float",
                    help="""Sets the precision of code tracking. Valid values are >1.0 and less than 8.0. Lower values represent more accurate tracking, but consume more CPU.""")

    parser.add_option('--flip',
                    dest="flip", default=False,
                    action='store_true',
                    help="""Flip the video image horizontally before processing.""")

    parser.add_option('-m','--max_cards',
                    dest="tracker_count", default=3, type="int",
                    action="store",
                    help="""The number of simultaneous snap codes that can be tracked in the video stream.""")


    parser.add_option('--nv','--no_video',
                    dest="no_video", default=False, 
                    action="store_true",
                    help="""A debugging option, turns off the video stream from the web cam.""")

    parser.add_option('-d','--debug',
                    dest="debug", default=False, 
                    action="store_true",
                    help="""Debugging option, turns on fps display and additional tracking data on the display.""")


    opts, args = parser.parse_args()

    import os
    os.environ['SDL_VIDEODRIVER'] = 'windib'
    if opts.hw_accel:
        os.environ['SDL_VIDEODRIVER'] = 'directx'
        opts.fullscreen = True

    # initialize pygame
    pygame.init()

    display_size = (800,600)
    video_size = (1280,720)
    
    # scale is roughly equivalent to tracking precision
    # the higher the scale, the less precise, but faster, the gross
    # tracking will be scale of 1 means 1:1 tracking, but can be slow
    # recommend 2-4 as a good scale/precision factor. higher res images
    # usually benefit from higher scale
    scale = opts.scale
    
    
    # this can be used to throttle the max framerate processed. 0 means no throttle
    max_frame_rate = 30
    
    names =  [args[0]]
    name = names[0]

    if not opts.no_video:
        # connect to web camera and set the webcam options
        capture = cvCreateCameraCapture( int(name) )
        cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, video_size[0] )
        cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, video_size[1] )
    
        # query the camera once to get the camera properties
        # the frame is just a throwaway
        cvQueryFrame( capture )

        # get the camera properties
        (o_width,o_height) = [cvGetCaptureProperty(capture, prop) for prop in [CV_CAP_PROP_FRAME_WIDTH,CV_CAP_PROP_FRAME_HEIGHT]]
        video_size = (int(o_width),int(o_height))
    else:
        blank = cvCreateImage(video_size,8,3)
        cvZero(blank)

    # create the pygame display
    flags = 0
    if opts.fullscreen:
        flags = pygame.FULLSCREEN
    if opts.hw_accel:
        flags = flags|pygame.HWSURFACE|pygame.DOUBLEBUF

    display_layer = pygame.display.set_mode( display_size,  flags ) 

    video = pygame.Surface(video_size).convert()

    # set the window name
    pygame.display.set_caption('Live Detector') 

    # some debug information
    # print the current driver being used
    print 'Driver %s\nVideo Input Resolution: %s\nDisplay Resolution: %s\n' % (pygame.display.get_driver(), video_size, display_size)

    # for convert to work, pygame video mode has to be set
    image_buffer = ImageBuffer(video_size,display_size,scale)
    if opts.no_video:
        image_buffer.frame_buffer = cvCreateImage(video_size,8,3)
        # blank = cvCreateImage(video_size,8,3)
        # cvZero(blank)
    worker = GrossTracker(image_buffer) 
    
    # pool of tracker objects
    pool = TrackerPool(image_buffer, opts.tracker_count)
    thread_objects.append(pool)


    status = Status()
    
    connector = Connector(pool,status)
    connector.start()
    thread_objects.append(connector)
    
    # for i in range(4):
    #     win_name = "thread-%d" % i
    #     cvNamedWindow(win_name, CV_WINDOW_AUTOSIZE)
    
    pyg_clock = pygame.time.Clock()
    update_count = 0
    last_rects = []
    last_fills = []
    hud_last_fills = []

    if opts.debug:
        dbg = DebugDisplay()

    snap_logo = pygame.image.load('./images/snap_logo.png').convert_alpha()
    
    still = False
    running = True
    fps = 0.0
    while running:
        pyg_clock.tick(max_frame_rate)
        if update_count > 20:
            fps = pyg_clock.get_fps()
            update_count = 0
        update_count += 1

        # get the pygame events
        events = pygame.event.get()
        for e in events:
            # 'quit' event key
            if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
                running = False
            elif e.type == KEYDOWN and e.unicode == u't':
                still = True
            
            
        # take a frame from the web camera
        if opts.no_video:
            cvCopy(blank,image_buffer.frame_buffer)
        else:
            image_buffer.frame_buffer = cvQueryFrame( capture )

        if opts.flip:
            cvFlip(image_buffer.frame_buffer,image_buffer.frame_buffer,1)
            
        # update the image buffer with the latest frame
        image_buffer.update()

        # analyze the small frame to find collapsed candidates
        squares = worker.analyze_frame()        

        # check squares and assign a tracker if new
        pool.check(squares)
        # update all trackers
        pool.update()

        status.update()
        
        # clear the paint buffer
        for rect in last_rects:
            pygame.gfxdraw.rectangle(image_buffer.paint_buffer, rect, Color(0,0,0))
        last_rects = []
        
        for blank in last_fills:
            image_buffer.paint_buffer.fill((0,0,0),blank)
        last_fills = []


        for blank in hud_last_fills:
            image_buffer.hud_buffer.fill((0,0,0,0),blank)
        hud_last_fills = []



        # draw the sprite and tracker boundaries
        # boundaries will be replaced (or turned off)
        pool.sort_active()
        for t_id in pool.active_trackers:
            #rect = pool.trackers[t_id].get_bound_rect()
            center = pool.trackers[t_id].get_avg_center(2)

            frame_color = Color(128,255,128)
            if pool.trackers[t_id].sprite:
                # print str(dir(pool.trackers[t_id].sprite))
                sprite_size = pool.trackers[t_id].sprite.get_size()
                # print str(sprite_size)
                x_diff = sprite_size[0] / 2.0
                y_diff = sprite_size[1] / 2.0
                
                # frame_color = Color(250,250,255)
                
                rect = pygame.Rect(center.x * image_buffer.display_scale[0] - x_diff, center.y * image_buffer.display_scale[1] - y_diff, sprite_size[0],sprite_size[1])
                # pygame.gfxdraw.rectangle(image_buffer.paint_buffer, rect, pool.trackers[t_id].color)
                # last_rects.append(rect)
                #if pool.trackers[t_id].user_id:
                image_buffer.paint_buffer.blit(pool.trackers[t_id].sprite,(rect.x ,rect.y ))
                last_fills.append(rect) #pygame.Rect(rect.x ,rect.y ,closer_img.size[0],closer_img.size[1]))
            else:
                # rect = pygame.Rect(center.x * scale - 100, center.y * scale - 100, 200,200)
                # 
                # 
                # pygame.gfxdraw.rectangle(image_buffer.paint_buffer, rect, frame_color)
                # last_rects.append(rect)

                #c = pygame.Color(164,229,135,150)
                #c1 = pygame.Color(164,229,135,255)
                c = pygame.Color(229,229,135,200)
                # c1 = pygame.Color(229,229,135,255)

                pygame.gfxdraw.filled_polygon(image_buffer.hud_buffer, pool.trackers[t_id].get_bounding_points(),c)
                # pygame.gfxdraw.polygon(image_buffer.hud_buffer, pool.trackers[t_id].get_bounding_points(),c1)
                # pygame.gfxdraw.rectangle(image_buffer.hud_buffer, rect, frame_color)
                # pygame.gfxdraw.filled_polygon(image_buffer.hud_buffer, pool.trackers[t_id].get_bounding_points(),c)
                hud_last_fills.append(pool.trackers[t_id].get_bound_rect())
                


        # draw the orphans and frame rate display
        # debug for now, lets me know when it's trying to lock onto something
        if opts.debug:
            fps_sprite = dbg.gen_sprite('''%.2f fps''' % fps)
            image_buffer.hud_buffer.blit(fps_sprite,(image_buffer.display_size[0]-100,10))
            fps_rect = pygame.Rect(video_size[0]-100,10, dbg.size[0], dbg.size[1])
            hud_last_fills.append(fps_rect)
            
            for orphans in pool.orphan_frames:
                for orphan in orphans:
                    orphan = pygame.Rect(orphan.x * image_buffer.display_scale[0], orphan.y * image_buffer.display_scale[1], orphan.width * image_buffer.display_scale[0], orphan.height * image_buffer.display_scale[1])
                    pygame.gfxdraw.rectangle(image_buffer.paint_buffer, orphan, Color(190,255,190))
                    last_rects.append(orphan)

        # no data in the frame buffer means we're done
        if not image_buffer.frame_buffer:
            break

        # Surf_dat array is not oriented the same way as the pyame display so
        # first it's transposed. Then the
        # the surface RGB values are not the same as the cameras
        # this means that two of the channels have to be swapped in the numpy
        # array before being blit'ted onto the array
        surf_dat = image_buffer.frame_buffer.as_numpy_array().transpose(1,0,2)[...,...,::-1]
        
        # blit_array zaps anything on the surface and completely replaces it with the array, much
        # faster than converting the bufer to a surface and bliting it
        # replaces video with the data in surf_dat
        surfarray.blit_array(video,surf_dat)
        
        # this resizes the video surface and stores it in display_layer. Completely
        # overwrites whatever is in display_layer
        pygame.transform.scale(video, image_buffer.display_size, display_layer)
        
        # blit the paint buffer onto the surface. Paint buffer has a chromakey so all black values will show through
        display_layer.blit(image_buffer.paint_buffer,(0,0))

        # the "HUD" is added next. 
        display_layer.blit(image_buffer.hud_buffer,(0,0))

        # Write out the status sprite to the display_layer
        if status.sprite:
            display_layer.blit(status.sprite,(10,image_buffer.display_size[1] - status.height - 10 ))


        # finally watermark the screen with the company logo and name of the product
        # putting it here means it always shows above the other layers
        logo_size = snap_logo.get_size()
        display_layer.blit(snap_logo,(image_buffer.display_size[0]-logo_size[0]-10 , image_buffer.display_size[1]-logo_size[1]-10))


        if still == True:
            pygame.image.save(display_layer, 'test.jpg')
            still = False

        # flip() actually displays the surface
        pygame.display.flip()

    # we've left the loop
    # exit
    print 'exiting...'
Example #10
0
 def __init__(self, position=None):
     self.status = Status()
     self.position = position