Beispiel #1
0
    def Paint(self):
        scene = QGraphicsScene()

        # Draw the graph
        tt = self.ui.graphtype.currentIndex()
        if tt == 0:
            points = self.avgSpeed
        elif tt == 1:
            points = self.avgVolume
        elif tt == 2:
            points = self.avgCapacity
        elif tt == 3:
            points = self.avgRam
        p0 = points[0]
        for p in points[1:]:
            scene.addLine(5 + p0[0] * 2, 205 - p0[1] * 2, 5 + p[0] * 2,
                          205 - p[1] * 2, QPen(self.settings["graph"]))
            p0 = p

        # Draw the axis
        scene.addLine(5, 5, 5, 208, QPen(self.settings["axis"]))
        scene.addLine(2, 205, self.time * 2 + 5, 205,
                      QPen(self.settings["axis"]))
        t = 0
        while t <= self.time:
            scene.addLine(5 + t * 2, 206, 5 + t * 2, 204,
                          QPen(self.settings["axis"]))
            font = QFont()
            font.setPointSize(6)
            capt = scene.addText(str(t), font)
            capt.setPos(t * 2, 203)
            t += 10
        self.ui.graph.setScene(scene)
Beispiel #2
0
    def test(self):
        if not self.winManager:
            return
        from PyQt4.QtGui import QGraphicsScene, QGraphicsItem, QGraphicsLineItem
        from PyQt4.QtCore import QRectF, QLineF
        w = self.winManager.newWindow()
        scene = QGraphicsScene(w.graphicsView)
        scene.addItem(Items.Grid())
        scene.addItem(Items.Axes())

        line = scene.addLine(QLineF(0, 0, 0, 0))

        cross = Items.NodeCross(movable=True)
        cross.addEdge(line, 1)
        scene.addItem(cross)

        help = scene.addText(QCoreApplication.translate('Graphics', 'Press "h" for help!'))
        help.moveBy(-50, 80)

        text = Items.NodeText(QCoreApplication.translate('Graphics', 'Drag Me!'))
        text.setFlag(QGraphicsItem.ItemIsMovable, True)
        text.setFlag(QGraphicsItem.ItemIsSelectable, True)
        text.addEdge(line, 2)
        scene.addItem(text)
        w.graphicsView.setScene(scene)
    def Paint(self):
        scene = QGraphicsScene()

        # Draw the graph
        tt = self.ui.graphtype.currentIndex()
        if tt == 0:
            points = self.avgSpeed
        elif tt == 1:
            points = self.avgVolume
        elif tt == 2:
            points = self.avgCapacity
        elif tt == 3:
            points = self.avgRam
        p0 = points[0]
        for p in points[1:]:
            scene.addLine(5 + p0[0] * 2, 205 - p0[1] * 2, 5 + p[0] * 2, 205 - p[1] * 2, QPen(self.settings["graph"]))
            p0 = p

        # Draw the axis
        scene.addLine(5, 5, 5, 208, QPen(self.settings["axis"]))
        scene.addLine(2, 205, self.time * 2 + 5, 205, QPen(self.settings["axis"]))
        t = 0
        while t <= self.time:
            scene.addLine(5 + t * 2, 206, 5 + t * 2, 204, QPen(self.settings["axis"]))
            font = QFont()
            font.setPointSize(6)       
            capt = scene.addText(str(t), font)
            capt.setPos(t * 2, 203)
            t += 10
        self.ui.graph.setScene(scene)
    def Paint(self):
        scene = QGraphicsScene()
        scene.setBackgroundBrush(Qt.transparent)
        scene.addLine(5, 5, 5, 213, QPen(self.settings["axis"]))
        scene.addLine(2, 210, 210, 210, QPen(self.settings["axis"]))
        mod_num = int(self.ui.moduleNum.currentText())
        max_sim = max(self.points_sim, key=lambda x: x[mod_num])[mod_num]
        max_mm = max(self.points_mm, key=lambda x: x[mod_num])[mod_num]
        max_time = max(max_mm, max_sim)

        for i in range(10):
            scene.addLine(4, 210 - (i + 1) * 20, 6, 210 - (i + 1) * 20, QPen(self.settings["axis"]))
            font = QFont()
            font.setPointSize(6)
            if int(0.1*max_time*(i + 1)) != 0:
                t2 = scene.addText(str(int(0.1*max_time*(i + 1))), font)
                t2.setPos(-18, 200 - (i + 1) * 20)

        i = 1
        x0 = 5 + 200 / self.num
        y0 = 210 - float(self.points_mm[0][mod_num]) / max_time * 200
        for p in self.points_mm:
            x = 5 + i * 200 / self.num
            y = 210 - float(p[mod_num])/max_time * 200
            scene.addLine(x0, y0, x, y, QPen(self.settings["mm"]))
            scene.addLine(x - 2, y - 2, x + 2, y + 2, QPen(self.settings["mm"]))
            scene.addLine(x + 2, y - 2, x - 2, y + 2, QPen(self.settings["mm"]))
            x0 = x
            y0 = y
            i += 1
        i = 1
        x0 = 5 + 200 / self.num
        y0 = 210 - float(self.points_sim[0][mod_num]) / max_time * 200
        for p in self.points_sim:
            x = 5 + i * 200 / self.num
            y = 210 - float(p[mod_num])/max_time * 200
            scene.addLine(x0, y0, x, y, QPen(self.settings["sim"]))
            scene.addLine(x - 2, y - 2, x + 2, y + 2, QPen(self.settings["sim"]))
            scene.addLine(x + 2, y - 2, x - 2, y + 2, QPen(self.settings["sim"]))
            x0 = x
            y0 = y
            i += 1
        self.ui.graph.setScene(scene)

        self.ui.table.setRowCount(len(self.simplesystems))
        self.simplesystems.sort(key = lambda x: x.simrel)
        for i in range(len(self.simplesystems)):
            self.ui.table.setItem(i, 0, QTableWidgetItem(self.simplesystems[i].id))
        self.simplesystems.sort(key = lambda x: x.mmrel)
        for i in range(len(self.simplesystems)):
            self.ui.table.setItem(i, 1, QTableWidgetItem(self.simplesystems[i].id))
            if self.ui.table.item(i, 0).text() != self.ui.table.item(i, 1).text():
                self.ui.table.item(i, 0).setForeground(QBrush(QColor(255,0,0)))
                self.ui.table.item(i, 1).setForeground(QBrush(QColor(255,0,0)))
            else:
                self.ui.table.item(i, 0).setForeground(QBrush(QColor(0,255,0)))
                self.ui.table.item(i, 1).setForeground(QBrush(QColor(0,255,0)))
        self.simplesystems.sort(key = lambda x: x.rel)
        for i in range(len(self.simplesystems)):
            self.ui.table.setItem(i, 2, QTableWidgetItem(self.simplesystems[i].id))
Beispiel #5
0
    def Paint(self):
        scene = QGraphicsScene()
        hor = self.ui.horizontal.currentIndex()
        vert = self.ui.vertical.currentIndex()
        v = {"a": [], "d": [], "c": [], "r": [], "f": []}
        h = {"a": [], "d": [], "c": [], "r": [], "f": []}
        for alg in self.algs:
            projects = []
            if hor == 0:
                projects = sorted(self.stats[alg].values(),key=lambda x: 1.0 / 3.0 * (x["computersload"] + x["storesload"] + x["ramload"]))
            elif hor == 1:
                projects = sorted(self.stats[alg].values(),key=lambda x: 0.5*(x["computersload"]+x["ramload"]))
            elif hor == 2:
                projects = sorted(self.stats[alg].values(),key=lambda x: x["computersload"])
            elif hor == 3:
                projects = sorted(self.stats[alg].values(),key=lambda x: x["ramload"])
            elif hor == 4:
                projects = sorted(self.stats[alg].values(),key=lambda x: x["storesload"])
            if projects == []:
                return
            for proj in projects:
                if vert == 0:
                    v[alg].append(proj["assigned"])
                elif vert == 1:
                    v[alg].append(proj["ratio"])
                elif vert == 2:
                    v[alg].append(proj["replicas"])
                if hor == 0:
                    h[alg].append(1.0 / 3.0 * (proj["computersload"] + proj["storesload"] + proj["ramload"]))
                elif hor == 1:
                    h[alg].append(0.5 * (proj["computersload"] + proj["ramload"]))
                elif hor == 2:
                    h[alg].append(proj["computersload"])
                elif hor == 3:
                    h[alg].append(proj["ramload"])
                elif hor == 4:
                    h[alg].append(proj["storesload"])

        maxnum = max([max(v[i]) for i in self.algs] + [1])
        scene.addLine(5, 5, 5, 213, QPen(self.settings["axis"]))
        scene.addLine(2, 210, 210, 210, QPen(self.settings["axis"]))
        for i in range(10):
            scene.addLine(5 + (i + 1) * 20, 209, 5 + (i + 1) * 20, 211, QPen(self.settings["axis"]))
            scene.addLine(4, 210 - (i + 1) * 20, 6, 210 - (i + 1) * 20, QPen(self.settings["axis"]))
            font = QFont()
            font.setPointSize(6)       
            t1 = scene.addText(str(0.1*(i + 1)), font)
            t1.setPos((i + 1) * 20, 212)
            if int(0.1*maxnum*(i + 1)) != 0:
                t2 = scene.addText(str(int(0.1*maxnum*(i + 1))), font)
                t2.setPos(-10, 200 - (i + 1) * 20)

        legendy = 10
        for alg in self.algs:
            x0 = h[alg][0]
            y0 = v[alg][0]
            color = QColor(random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))
            brush = QBrush(color)
            color = QPen(color)
            for x,y in zip(h[alg],v[alg]):
                scene.addLine(5 + x0 * 200, 210 - float(y0)/maxnum * 200, 5 + x * 200, 210 - float(y)/maxnum * 200, color)
                scene.addLine(5 + x * 200 - 2, 210 - float(y)/maxnum * 200 - 2 , 5 + x * 200 + 2, 210 - float(y)/maxnum * 200 + 2, color)
                scene.addLine(5 + x * 200 + 2, 210 - float(y)/maxnum * 200 - 2, 5 + x * 200 - 2, 210 - float(y)/maxnum * 200 + 2, color)
                x0 = x
                y0 = y
            scene.addRect(220, legendy, 5, 5, color, brush)
            t = scene.addText(algnames[alg], font)
            t.setPos(230, legendy-5)
            legendy += 10
        self.ui.graph.setScene(scene)
Beispiel #6
0
class Factura:
    def __init__(self,padre,num):
	self.padre=padre
	self.cursor=padre.cursor
	self.curser=padre.curser
	self.parent=padre
	self.num=num
	self.escena=QGraphicsScene()
	self.gvDocumento=QGraphicsView()
	#self.cfg=padre.cfg
	self.iniciar()

    def iniciar(self):
      if self.cargarPlantilla():
	iva=0
	subtotal=0
	total=0
	alto=int(self.cfg.get("documento", "alto"))
	ancho=int(self.cfg.get("documento", "ancho"))
	cfont=QFont("Droid Sans", int(self.cfg.get("cliente", "fuente")), int(self.cfg.get("cliente", "peso") ))
	pfont=QFont("Droid Sans", int(self.cfg.get("productos", "fuente")), int(self.cfg.get("productos", "peso") ))
	ffont=QFont("Droid Sans", int(self.cfg.get("fecha", "fuente")), int(self.cfg.get("fecha", "peso") ))
	tfont=QFont("Droid Sans", int(self.cfg.get("totales", "fuente")), int(self.cfg.get("totales", "peso") ))
	self.escena.setSceneRect(-int(self.cfg.get("documento", "x")),-int(self.cfg.get("documento", "y")),ancho,alto)
	fuente=QFont("Droid Sans", int(self.cfg.get("documento", "fuente")), int(self.cfg.get("documento", "peso") ))
	smallDroid=QFont("Droid Sans", 9)
	sql="""SELECT * FROM clientes as C, notas WHERE notas.id=%s and notas.cliente=C.id;"""%self.num
	self.curser.execute(sql)
	cliente=self.curser.fetchone()
	if cliente!=None:
	  cliente=dicursor(self.curser,cliente)
	datos=self.escena.addText("",cfont)
	datos.setHtml("<p><b>Nombre:</b> %s<br><b>Direccion:</b>  %s, C.P %s %s, %s.<br><b>RFC:</b>  %s</p>"%(cliente['nombre'],cliente['direccion'],cliente['correo'],cliente['poblacion'],cliente['estado'],cliente['rfc']))
	datos.setPos(int(self.cfg.get("cliente", "x")) ,int(self.cfg.get("cliente", "y")))
	datos.setTextWidth(int(self.cfg.get("cliente", "ancho")))
	self.curser.execute("SELECT cantidad, `descripcion`,total/cantidad as precio,total,porcentaje as imp,unidades.nombre as unidad, ' ' as espacio  from productos,vendidos, impuestos , unidades where ref=producto and venta="+str(self.num)+" and impuestos.id=impuesto and unidades.id=unidad group by ref")
	fecha=self.escena.addText("",ffont)
	if isinstance(cliente['fecha'],datetime.datetime):
	  fecha.setHtml(cliente['fecha'].strftime(self.cfg.get("fecha", "formato")))
	else:
	  fecha.setHtml(datetime.datetime.strptime(cliente['fecha'],'%Y-%m-%d %H:%M:%S').strftime(self.cfg.get("fecha", "formato")))
	fecha.setPos(int(self.cfg.get("fecha", "x")),int(self.cfg.get("fecha", "y")))
	fecha.setTextWidth(int(self.cfg.get("fecha", "ancho")))
	#print "SELECT cantidad, `descripcion`,precio,total from productos,vendidos where ref=producto and venta="+str(self.num)+" group by ref"
	arts=self.curser.fetchall()
	if arts!=None:
	  arts=dicursor(self.curser,arts)
	  col=[[],[],[],[],[]]
	  #dict(arts)
	  for item in arts:
	    imp=0;porc=0
	    imp=item['total']/float("1.%d"%item['imp'])
	    porc=imp*(int(item['imp'])*.01)
	    #imp=round(imp,2)
	    #porc=round(porc,2)
	    #porc+=item['total']-(imp+porc)
	    total+=item['total']
	    item['precio']=round(imp/item['cantidad'],2)
	    item['total']=round(imp,2) 
	    iva+=porc
	    subtotal+=imp
	  subtotal=round(subtotal,2)
	  iva=round(iva,2)
	  filas=[]
	  campos=self.cfg.get("productos", "campos").replace(" ","").split(",")
	  heads="{%s}"%"},{".join(campos)
	  anchos=self.cfg.get("productos", "anchos").replace(" ","").split(",")
	  #cabezas=heads.replace("{","").replace("}","").split(",")
	  for item in arts:
	      row=heads.format(**item)
	      filas.append(row.split(','))

	  heads=heads.replace("{","").replace("}","") 
	  tabla=self.escena.addText("",pfont)
	  tabla.setHtml(listaHtml(filas,cabezas=campos,color='#fff',fondo="#FFF", tfuente=11,opc="101",css="th{color:#FFF} .celda{margin:10px;padding:5px;}",anchos=anchos))
	  tabla.setPos(int(self.cfg.get("productos", "x")),int(self.cfg.get("productos", "y")))
	  tabla.setTextWidth(int(self.cfg.get("productos", "ancho")))

	cantidad=self.escena.addText("",pfont)
	cantidad.setHtml("<center>%s</center>"%nletra(total))
	cantidad.setPos(int(self.cfg.get("nletra", "x")),int(self.cfg.get("nletra", "y")))
	cantidad.setTextWidth(int(self.cfg.get("nletra", "ancho")))
	totales=self.escena.addText("",tfont)
	totales.setHtml("<p ALIGN=right>%.2f</p><p ALIGN=right>%.2f</p><p ALIGN=right>%.2f</p>"%(float(subtotal),float(iva),float(total)))
	totales.setPos(int(self.cfg.get("totales", "x")),int(self.cfg.get("totales", "y")))
	totales.setTextWidth(int(self.cfg.get("totales", "ancho")))
	#self.curser.execute("SELECT cantidad, `descripcion`,precio,total from productos,vendidos where ref=producto and venta="+str(self.num)+" group by ref")
	
	self.gvDocumento.setScene(self.escena)
      else:
	print "Error al cargar plantilla"
	
    def alinear(self,item):
      formato=QTextBlockFormat()
      formato.setAlignment(Qt.AlignRight)
      cursor = item.textCursor()
      cursor.select(QTextCursor.Document)
      cursor.mergeBlockFormat(formato)
      cursor.clearSelection()
      item.setTextCursor(cursor)

    def cargarPlantilla(self):
	self.cfg = Cp.ConfigParser()
	if self.cfg.read([os.path.join(home,"formas","factura.cfg")]):
	  if self.cfg.has_option("documento", "version"):
	    return True
	else:
	  return False
    
	
    def br(self,texto):
	 offset=1
	 font=texto.font()
	 pos=texto.pos()
	 return QPointF(pos.x(),float(pos.y())+float(font.pointSize())+offset)

    def imprimir(self):
      	printer=QPrinter(QPrinter.HighResolution)
	printer.setPaperSize(QPrinter.Letter)   
	printer.setOutputFormat(QPrinter.PdfFormat)
	ruta=os.path.join(self.parent.cfg.get("factura", "ruta"),'Factura-'+str(self.num)+'.pdf')
	printer.setOutputFileName(ruta)
	prev=QPrintDialog(printer,self.padre)
	if prev.exec_()==QDialog.Accepted:
	    paint=QPainter()
	    paint.begin(printer)
	    self.escena.render(paint)
	    paint.end()
	    print "Imprimiendo..."
	    
	if sys.platform == 'linux2':
	    os.system("gnome-open '%s' "%ruta)
	elif sys.platform == 'win32':
	    os.system("start '%s'"%ruta)
Beispiel #7
0
class ImageGrabber(object):
    '''
    classdocs
    '''
    _config = mrConfigParser()
    _gui = GuiLoader()
    _img = None
    __sources = []
    __grabTimer = QTimer()

    __scene = None
    __gview = None

    def __init__(self, gui=None, config=None):
        '''
        Constructor
        '''
        self._gui = GuiLoader()
        self._config = config

        if gui != None:
            self._gui = gui
            self.__initGui()

    def __initGui(self):
        '''
        Initiates gui listeners
        '''
        # initiate scene
        self.__gview = self._gui.getObj("imgVideo")
        self.__scene = QGraphicsScene()
        self.__gview.setScene(self.__scene)

        # add image size combobox items
        cmb = self._gui.getObj("cmbImgSize")
        cmb.addItem("320x240")
        cmb.addItem("640x480")
        cmb.addItem("800x600")
        cmb.addItem("1024x768")
        #cmb.addItem("1280x960")        # not working with libdc1394 and avt stringray 125c

        # add conversion combobox items
        cmb = self._gui.getObj("cmbConversion")
        cmb.addItem("None")
        cmb.addItem("COLOR_BGR2RGB")
        cmb.addItem("COLOR_GRAY2RGB")
        cmb.addItem("COLOR_YUV2RGB")
        cmb.addItem("COLOR_HLS2RGB")

        # add listeners
        self._gui.connect("cmdStartVideo", "clicked()", self.startVideo)
        self._gui.connect("cmdStopVideo", "clicked()", self.stopVideo)
        self._gui.connect("cmdAddSource", "clicked()", self.__addCamSource)
        self._gui.connect("cmdAddFile", "clicked()", self.__addFileSource)
        self._gui.connect("cmdDelSource", "clicked()",
                          self.__removeSourceFromList)
        self._gui.connect("cmbImgSize", "currentIndexChanged(QString)",
                          self.__imageSizeChanged)
        self._gui.connect("cmdSaveImg", "clicked()", self.saveImg)

    def isActive(self):
        '''
        @return: True if image grabbing is active
        '''
        return self.__grabTimer.isActive()

    def startVideo(self):
        '''
        Starts grabbing images
        '''
        if self.__grabTimer.isActive():
            self.__grabTimer.stop()

        self.__grabTimer = QTimer()
        self.__grabTimer.timeout.connect(self.__grabImage)
        self.__grabTimer.start(0)
        self._gui.status("Video started")

    def stopVideo(self):
        '''
        Stops grabbing video
        '''
        if self.__grabTimer.isActive():
            self.__grabTimer.stop()
            self.__scene.clear()
            self.__gview.show()
            self._gui.status("Video stopped")
            sleep(1)

    def getImage(self):
        '''
        Returns the last grabbed image
        @return: Image
        '''
        return self._img

    def saveImg(self):
        '''
        Saves image
        '''
        if self._img != None:
            img = self._img

            # stop video
            active = self.isActive()
            self.stopVideo()

            # open file dialog
            options = copy(self._gui.dialogOptionsDef)
            options['type'] = self._gui.dialogTypes['FileSave']
            options['filetypes'] = "JPG (*.jpg)"
            options['title'] = "Save current frame as"
            src = str(self._gui.dialog(options))

            # check filepath and save
            if len(src) > 0:
                if not src.endswith(".jpg"):
                    src = src + ".jpg"
                self._gui.status("write to " + src)
                cvtColor(img, COLOR_BGR2RGB)
                imwrite(src, img)

            # reset video streaming
            if active:
                self.startVideo()

    def __showImage(self):
        '''
        Shows image on graphics view
        '''
        if self._img != None:
            self.__scene.clear()
            self.__scene.addPixmap(imageToPixmap(self._img))
            self.__gview.fitInView(self.__scene.sceneRect(),
                                   Qt.KeepAspectRatio)
            self.__gview.show()

    def __grabImage(self):
        '''
        Graps image from sources
        '''
        images = []

        # grab all images
        for src in self.__sources:
            assert isinstance(src, AbstractSourceGrabber)
            images.append(src.getImg())

        # join and convert images
        img = self.__joinImages(images)

        # convert image
        convert = eval(str(self._gui.getObj("cmbConversion").currentText()))
        if convert != None:
            try:
                img = cvtColor(img, convert)
            except:
                img = None

        # show results
        if type(img) == ndarray:
            # add image as new image
            self._img = img
            self.__showImage()

        else:
            # show message
            self.__scene.clear()
            self.__scene.addText("NO VIDEO")

    def __joinImages(self, images=[]):
        '''
        Joins images
        '''
        # TO-DO: Joining images
        if len(images) > 0:
            return images[0]
        return False

    def __imageSizeChanged(self, size="640x480"):
        '''
        Changes image size
        '''
        size = str(size).split("x")
        w = int(size[0])
        h = int(size[1])

        # set size
        for cam in self.__sources:
            if type(cam) == CamGrabber:
                assert isinstance(cam, CamGrabber)
                cam.setImgSize(w, h)

    def __addSourceToList(self, grabber=None):
        '''
        Adds source to source list
        '''
        assert isinstance(grabber, AbstractSourceGrabber)

        if grabber != None:
            # add grabber to list
            self.__sources.append(grabber)
            txt = None

            # get type of grabber
            if type(grabber) == CamGrabber:
                txt = "cam [" + str(grabber.getSource()) + "]"
            elif type(grabber) == FileGrabber:
                txt = "file [" + str(grabber.getSource()) + "]"

            # add text string to gui list
            if txt != None:
                self._gui.getObj("lstSources").addItem(txt)

    def __removeSourceFromList(self):
        '''
        Removes selected source from list
        '''
        for item in self._gui.getObj("lstSources").selectedItems():
            # get item informationen
            txt = str(item.text())
            if "[" in txt and "]" in txt:
                data = txt.split("[")
                iType = data[0].strip()
                iSource = data[1].replace(']', '')

                # search for grabber
                for grabber in self.__sources:
                    assert isinstance(grabber, AbstractSourceGrabber)

                    if str(grabber.getSource()) == iSource:
                        if type(grabber) == CamGrabber and iType == "cam":
                            self.__sources.remove(grabber)
                            break
                        elif type(grabber) == FileGrabber and iType == "file":
                            self.__sources.remove(grabber)
                            break

                # remove source from gui list
                item = self._gui.getObj("lstSources").takeItem(
                    self._gui.getObj("lstSources").currentRow())
                item = None

    def __addCamSource(self):
        '''
        Adds camera as source
        '''
        obj = self._gui.getObj("txtSource")
        source = int(obj.text())

        grabber = CamGrabber(source)
        if grabber.isOpened():
            self.__addSourceToList(grabber)
            self._gui.status("Added camera source [" + str(source) + "]")
        else:
            self._gui.status(
                "Could not add camera source [" + str(source) + "]",
                self._gui.msgTypes['ERROR'])

    def __addFileSource(self):
        '''
        Adds file as source
        '''
        self.stopVideo()
        options = copy(self._gui.dialogOptionsDef)
        options['filetypes'] = "Images (*.jpg *jpeg *gif *png *bmp *tif)"
        source = str(self._gui.dialog(options))

        if len(source) > 0:
            grabber = FileGrabber(source)
            self.__addSourceToList(grabber)

            self._gui.status("Added file source [" + str(source) + "]")
class Canvas(QGraphicsView):
    def __init__(self, window, resultDict, imagePath):
        QGraphicsView.__init__(self)
        self.window = window
        self.pen = QPen(QColor("red"))
        self.pen.setWidth(0.5)
        self.canvasScene = QGraphicsScene()
        self.setScene(self.canvasScene)
        self.resultDict = resultDict
        self.imagePath = imagePath
        self.setBackgroundBrush(QBrush(Qt.black, Qt.SolidPattern))

    def drawImage(self, imageFile):
        """Draw an image on the canvas"""
        image = QPixmap(imageFile)
        self.canvasScene.addPixmap(image)
        return image

    def drawFeaturePoint(self, pointList):
        """Draw a feature point on the canvas"""
        radius = 0.5
        width, height = 2, 2

        x1, y1, x2, y2 = pointList

        #Draw ellipse and bounding rect. Is a hacked version!
        self.canvasScene.addEllipse(x1 - radius + 5, y1 - radius + 3, 2 * radius, 2 * radius, self.pen)
        self.canvasScene.addEllipse(x2 - radius + self.imageWidth + 10, y2 - radius + 3, 2 * radius, 2 * radius, self.pen)
        self.canvasScene.addRect(x1 - width / 2. + 5, y1 - height / 2. + 3, width, height, self.pen)
        self.canvasScene.addRect(x2 - width / 2. + self.imageWidth + 10, y2 - height / 2. + 3, width, height, self.pen)

    def drawFeatureImages(self, imageFile):
        """Draw two consecutive images on the screen"""
        #Load image files
        path, file_ = os.path.split(imageFile)
        image1 = QPixmap(os.path.join(path, 'first_' + file_))
        image2 = QPixmap(os.path.join(path, 'second_' + file_))
        self.imageWidth = image1.width()

        #Add pixmaps
        image1Map = self.canvasScene.addPixmap(image1)
        image2Map = self.canvasScene.addPixmap(image2)

        #Shift pixmaps to the right position
        image1Map.setOffset(QPointF(5, 3))
        image2Map.setOffset(QPointF(10 + image1.width(), 3))

    def drawPolygon(self, Polygon):
        """Draw a polygon on the canvas"""
        polygon = QPolygonF()
        for point in Polygon:
            polygon.append(QPointF(point[0], point[1]))
        self.canvasScene.addPolygon(polygon, self.pen)

    def getWorkerId(self):
        return self.resultDict.values()[self.index][0][0]

    def getAssignmentId(self):
        return self.resultDict.keys()[self.index]

    def nextImage(self):
        """Load next image"""
        self.index += 1
        self.canvasScene.clear()
        if self.index > len(self.resultDict) - 1 or len(self.resultDict) <= 0:
            self.canvasScene.addText("No annotations to review")
            self.window.reviewFlag = False
            self.window.updateTable()

        else:
            #Draw Image and Polygon
            assignmentId = self.resultDict.keys()[self.index]
            result = self.resultDict[assignmentId]
            image = result[0][1]
            pointList = result[0][2]
            if self.window.segmentation_mode:
                pointList = [round(float(point), 3) for point in pointList]
                pointList = zip(*[iter(pointList)] * 2)
                self.drawImage(os.path.join(self.imagePath, image))
                self.drawPolygon(pointList)
            else:
                pointList = [round(float(point), 3) for point in pointList]
                pointList = zip(*[iter(pointList)] * 4)
                self.drawFeatureImages(os.path.join(self.imagePath, image))
                for point in pointList:
                    self.drawFeaturePoint(point)

        #update scene
        self.window.setWindowTitle("MTurk Review Tool ({0}/{1})   Rejected: {2}   Approved: {3}".format(self.index + 1,
                                        len(self.resultDict), len(self.window.rejected), len(self.window.approved)))
        self.canvasScene.setSceneRect(self.canvasScene.itemsBoundingRect())
        self.fitInView(0, 0, self.canvasScene.width(), self.canvasScene.height(), 1)    
        self.canvasScene.update(0, 0, self.canvasScene.width(), self.canvasScene.height())
Beispiel #9
0
    def Paint(self):
        scene = QGraphicsScene()
        hor = self.ui.horizontal.currentIndex()
        vert = self.ui.vertical.currentIndex()
        v = {"a": [], "d": [], "c": [], "r": [], "f": []}
        h = {"a": [], "d": [], "c": [], "r": [], "f": []}
        for alg in self.algs:
            projects = []
            if hor == 0:
                projects = sorted(self.stats[alg].values(),key=lambda x: 1.0 / 3.0 * (x["computersload"] + x["storesload"] + x["ramload"]))
            elif hor == 1:
                projects = sorted(self.stats[alg].values(),key=lambda x: 0.5*(x["computersload"]+x["ramload"]))
            elif hor == 2:
                projects = sorted(self.stats[alg].values(),key=lambda x: x["computersload"])
            elif hor == 3:
                projects = sorted(self.stats[alg].values(),key=lambda x: x["ramload"])
            elif hor == 4:
                projects = sorted(self.stats[alg].values(),key=lambda x: x["storesload"])
            if projects == []:
                return
            for proj in projects:
                if vert == 0:
                    v[alg].append(proj["assigned"])
                elif vert == 1:
                    v[alg].append(proj["ratio"])
                elif vert == 2:
                    v[alg].append(proj["replicas"])
                if hor == 0:
                    h[alg].append(1.0 / 3.0 * (proj["computersload"] + proj["storesload"] + proj["ramload"]))
                elif hor == 1:
                    h[alg].append(0.5 * (proj["computersload"] + proj["ramload"]))
                elif hor == 2:
                    h[alg].append(proj["computersload"])
                elif hor == 3:
                    h[alg].append(proj["ramload"])
                elif hor == 4:
                    h[alg].append(proj["storesload"])

        maxnum = max([max(v[i]) for i in self.algs] + [1])
        scene.addLine(5, 5, 5, 213, QPen(self.settings["axis"]))
        scene.addLine(2, 210, 210, 210, QPen(self.settings["axis"]))
        for i in range(10):
            scene.addLine(5 + (i + 1) * 20, 209, 5 + (i + 1) * 20, 211, QPen(self.settings["axis"]))
            scene.addLine(4, 210 - (i + 1) * 20, 6, 210 - (i + 1) * 20, QPen(self.settings["axis"]))
            font = QFont()
            font.setPointSize(6)       
            t1 = scene.addText(str(0.1*(i + 1)), font)
            t1.setPos((i + 1) * 20, 212)
            if int(0.1*maxnum*(i + 1)) != 0:
                t2 = scene.addText(str(int(0.1*maxnum*(i + 1))), font)
                t2.setPos(-10, 200 - (i + 1) * 20)

        legendy = 10
        for alg in self.algs:
            x0 = h[alg][0]
            y0 = v[alg][0]
            color = QColor(random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))
            brush = QBrush(color)
            color = QPen(color)
            for x,y in zip(h[alg],v[alg]):
                scene.addLine(5 + x0 * 200, 210 - float(y0)/maxnum * 200, 5 + x * 200, 210 - float(y)/maxnum * 200, color)
                scene.addLine(5 + x * 200 - 2, 210 - float(y)/maxnum * 200 - 2 , 5 + x * 200 + 2, 210 - float(y)/maxnum * 200 + 2, color)
                scene.addLine(5 + x * 200 + 2, 210 - float(y)/maxnum * 200 - 2, 5 + x * 200 - 2, 210 - float(y)/maxnum * 200 + 2, color)
                x0 = x
                y0 = y
            scene.addRect(220, legendy, 5, 5, color, brush)
            t = scene.addText(algnames[alg], font)
            t.setPos(230, legendy-5)
            legendy += 10
        self.ui.graph.setScene(scene)
Beispiel #10
0
class Printer(object):
	"""For printing in diferent card formats and sizes the associated deck, be it to the screen or pdfs or image files"""

	card_sizes = {"Jumbo":(3.5,5.5), "Tarot":(2.75,4.75), "Square":(3.5,3.5), "Poker":(2.5,3.5),
			 	  "Bridge":(2.25,3.5), "Biz":(2,3.5), "Mini":(1.75,2.5), "Micro":(1.25,1.75)}
	paper_sizes = {"A0":(33.1,46.8), "A1":(23.4,33.1), "A2":(16.5,23.4), "A3":(11.7,16.5),
				   "A4":(8.3,11.7), "A5":(5.8,8.3), "A6":(4.1,5.8)}
	#TODO paper margins when printing and centering the images

	def __init__(self, deck=None):
		self.deck = deck
		self.scene = QGraphicsScene()
		self.orientation = getattr(QPrinter, "Portrait")
		self.path = "output.pdf"
		self.paper = getattr(QPrinter, "A4")
		self.card_size = Printer.card_sizes["Poker"]

	def config(self, *args, **kwargs):
		"""kwargs: deck, card_size, paper_size, orientation, print_path
		if card_size is present I have to join the elements of the deck following the premises"""
		if "orientation" in kwargs:
			self.orientation = kwargs["orientation"]
		if "card_size" in kwargs:
			self.card_size = Printer.card_sizes[kwargs["card_size"][:kwargs["card_size"].find(" ")]]
		if "print_path" in kwargs:
			self.path = kwargs["print_path"]
		if "paper_size" in kwargs:
			self.paper = kwargs["paper_size"]
		if "deck" in kwargs:
			self.deck = kwargs["deck"]

	def print_grid(self):
		if self.deck is not None:
			#Setting the printer
			printer = QPrinter(QPrinter.HighResolution)
			printer.setOutputFormat(QPrinter.PdfFormat)
			printer.setOrientation(getattr(QPrinter, self.orientation))
			printer.setOutputFileName(self.path)
			printer.setPaperSize(getattr(QPrinter, self.paper))
			#Start printing
			with QPainter(printer) as paint:
				first = True
				for c in self.deck:
					if not first:
						printer.newPage()
					first = False
					self.preview_card(c)
					self.scene.render(paint)

	def max_cards(self):
		"""Taking in count the card_size, paper_size returns the max number of cards per page, horientation and margins"""
		port = {}
		port["orientation"] = "Portrait"
		pw = self.paper_sizes[self.paper][0]
		ph = self.paper_sizes[self.paper][1]
		port["horizontal"] = int(pw//self.card_size[0])
		port["vertical"] = int(ph//self.card_size[1])
		port["max"] = port["horizontal"] * port["vertical"]
		port["margin_horizontal"] = (pw % self.card_size[0]) / 2.0
		port["margin_vertical"] = (ph % self.card_size[1]) / 2.0
		land = {}
		land["orientation"] = "Landscape"
		pw = self.paper_sizes[self.paper][1]
		ph = self.paper_sizes[self.paper][0]
		land["horizontal"] = int(pw//self.card_size[0])
		land["vertical"] = int(ph//self.card_size[1])
		land["max"] = land["horizontal"] * land["vertical"]
		land["margin_horizontal"] = (pw % self.card_size[0]) / 2.0
		land["margin_vertical"] = (ph % self.card_size[1]) / 2.0
		if land["max"] > port["max"]:
			return land
		else:
			return port

	def print_pdf(self):
		if self.deck is not None:
			#Setting the printer
			printer = QPrinter(QPrinter.HighResolution)
			printer.setOutputFormat(QPrinter.PdfFormat)
			printer.setOrientation(getattr(QPrinter, "Portrait"))
			printer.setOutputFileName(self.path)
			printer.setPaperSize(getattr(QPrinter, self.paper))
			printer.setFullPage(True)
			guide = self.max_cards()
			printer.setOrientation(getattr(QPrinter, guide["orientation"]))
			print guide, self.card_size
			#Start printing
			with QPainter(printer) as paint:
				ind = 0
				resol = printer.resolution()
				for c in self.deck:
						c.resize(self.card_size[0], self.card_size[1])
						if ind == guide["max"]:
							printer.newPage()
							ind = 0

						col = ind % guide["horizontal"]
						fil = ind // guide["horizontal"]
						print ind, fil, col
						target = QRectF((col)*self.card_size[0]*resol, (fil)*self.card_size[1]*resol,
									self.card_size[0]*resol, self.card_size[1]*resol)

						self.preview_card(c)
						self.scene.render(paint, target=target, source=QRectF(0,0,c.width(),c.height()))
						ind += 1

	def save_images(self):
		if self.deck is not None:
			num = 1
			for c in self.deck:
				c.save_as("".join([str(self.path),str(num),".",c.format()]))
				num += 1

	def preview_card(self, card):
		try:
			self.scene.clear()
			ret = self.scene.addPixmap(card.pixmap())
		except:
			self.scene.clear()
			ret = self.scene.addText("Image not available")
		return ret