Exemplo n.º 1
0
    def _add_image(self, c: Component, slide):
        # Write image to temp folder
        with tempfile.TemporaryDirectory() as tmpdir:
            fname = c.data.make_raster(c.bounds.width, c.bounds.height,
                                       os.path.join(tmpdir, "image"))
            self._slide_mutex.acquire()
            shape = slide.shapes.add_picture(fname,
                                             Mm(c.bounds.left),
                                             Mm(c.bounds.top),
                                             width=Mm(c.bounds.width))
            shape.shadow.inherit = False
            self._slide_mutex.release()

        if c.has_frame:
            self._slide_mutex.acquire()
            offset = Pt(c.frame_linewidth) / 2
            shape = slide.shapes.add_shape(
                MSO_SHAPE.RECTANGLE,
                Mm(c.bounds.left) + offset,
                Mm(c.bounds.top) + offset,
                Mm(c.bounds.width) - Pt(c.frame_linewidth),
                Mm(c.bounds.height) - Pt(c.frame_linewidth))
            shape.shadow.inherit = False
            shape.line.color.rgb = RGBColor(c.frame_color[0], c.frame_color[1],
                                            c.frame_color[2])
            shape.line.width = Pt(c.frame_linewidth)
            # shape.line.join_type = 'Miter' # Removes rounded edges, but is not supported, yet (sadly)
            shape.fill.background()
            self._slide_mutex.release()
Exemplo n.º 2
0
def add_icon(ss, icon_name, left, top, small=False):
    ## ok if icon exists, and use error icon if not
    logger.debug("adding icon {}".format(icon_name))
    try:
        filename = icondir + icon_name + ".png"
        icon_width, icon_height = get_image_size(filename)
        pixels_per_mm = 6
        if small:
            icon_width = 0.4 * icon_width
            ss.add_picture(filename, round(left - icon_width / pixels_per_mm),
                           top, Mm(12), Mm(12))
        else:
            ss.add_picture(filename, round(left - icon_width / pixels_per_mm),
                           top, Mm(34), Mm(34))
    except:
        logger.warning("Could not find icon {}".format(icondir + icon_name +
                                                       '.png'))
    return
Exemplo n.º 3
0
    def exportNow(self, obj):
        if (obj.Gateway == 'PPTX') and not (obj.File == ''):
            from pptx.enum.shapes import MSO_CONNECTOR
            from pptx.util import Mm
            from pptx import Presentation

            prs = Presentation()
            title_slide_layout = prs.slide_layouts[0]
            slide = prs.slides.add_slide(title_slide_layout)
            title = slide.shapes.title
            subtitle = slide.placeholders[1]

            w, h = self.getPageSize(obj)
            w = w / 2
            h = h / 2
            for ln in self.LinesToPoints(obj):
                line1=slide.shapes.add_connector(MSO_CONNECTOR.STRAIGHT, Mm(ln[0][0]+w), Mm((ln[0][1]*-1.0)+h), Mm(ln[1][0]+w), Mm((ln[1][1]*-1.0)+h) )

            prs.save(obj.File)
Exemplo n.º 4
0
    def combine_rows(self, data: List[Component], bounds: Bounds):
        # We load a template from a file to have some nicer line styles etc by default
        # (they cannot currently be specified via python-pptx)
        with tempfile.TemporaryDirectory() as tmpdir:
            themedata = pkg_resources.read_binary(__package__, "theme.pptx")
            p = os.path.join(tmpdir, "theme.pptx")
            with open(p, "wb") as f:
                f.write(themedata)
            prs = Presentation(p)

        # Create a single slide presentation with a blank slide
        # prs = Presentation()
        prs.slide_height = Mm(bounds.height)
        prs.slide_width = Mm(bounds.width)
        blank_slide_layout = prs.slide_layouts[6]
        slide = prs.slides.add_slide(blank_slide_layout)

        # Add all our elements to the slide
        flat = []
        for row in data:
            flat.extend(row)

        # Generate all images in parallel
        futures = []
        for c in flat:
            if isinstance(c, ImageComponent):
                futures.append(
                    self._thread_pool.submit(self._add_image, c, slide))
        for f in futures:
            f.result()

        # Add everything else afterwards, to ensure proper z-order
        for c in flat:
            if isinstance(c, TextComponent):
                if c.rotation == 90.0 or c.rotation == -90.0:
                    # The shape is rotated about its center. We want a rotation about the top left corner instead.
                    # Since we only allow 90° rotations, we can correct for that with a simple translation
                    pos_top = c.bounds.top + c.bounds.height / 2. - c.bounds.width / 2.
                    pos_left = c.bounds.left - c.bounds.height / 2. + c.bounds.width / 2.

                    # swap height and width
                    height, width = c.bounds.width, c.bounds.height

                    shape = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE,
                                                   Mm(pos_left), Mm(pos_top),
                                                   Mm(width), Mm(height))
                    # tikz rotation is counter-clockwise, pptx clockwise (we switch in pptx)
                    shape.rotation = -c.rotation
                else:
                    shape = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE,
                                                   Mm(c.bounds.left),
                                                   Mm(c.bounds.top),
                                                   Mm(c.bounds.width),
                                                   Mm(c.bounds.height))

                shape.shadow.inherit = False

                # Background color
                if c.background_color is not None:
                    shape.fill.solid()
                    shape.fill.fore_color.rgb = RGBColor(
                        c.background_color[0], c.background_color[1],
                        c.background_color[2])
                else:
                    shape.fill.background()
                shape.line.fill.background()

                # Text properties
                text_frame = shape.text_frame
                p = text_frame.paragraphs[0]
                p.alignment = {
                    "center": PP_ALIGN.CENTER,
                    "left": PP_ALIGN.LEFT,
                    "right": PP_ALIGN.RIGHT
                }[c.horizontal_alignment]

                text_frame.margin_top = 0
                text_frame.margin_bottom = 0

                if c.horizontal_alignment == 'right':
                    text_frame.margin_right = Mm(c.padding.width_mm)
                    text_frame.margin_left = 0
                else:
                    text_frame.margin_right = 0
                    text_frame.margin_left = Mm(c.padding.width_mm)

                run = p.add_run()
                run.text = c.content.replace("\\\\", "\n")
                run.font.color.rgb = RGBColor(c.color[0], c.color[1],
                                              c.color[2])
                run.font.size = Pt(c.fontsize)

            if isinstance(c, RectangleComponent):
                shape = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE,
                                               Mm(c.bounds.left),
                                               Mm(c.bounds.top),
                                               Mm(c.bounds.width),
                                               Mm(c.bounds.height))
                shape.shadow.inherit = False
                shape.line.color.rgb = RGBColor(c.color[0], c.color[1],
                                                c.color[2])
                shape.line.width = Pt(c.linewidth)
                # shape.line.join_type = 'Miter' # Removes rounded edges, but is not supported, yet (sadly)
                shape.fill.background()

            if isinstance(c, LineComponent):
                shape = slide.shapes.add_connector(MSO_CONNECTOR.STRAIGHT,
                                                   Mm(c.from_x), Mm(c.from_y),
                                                   Mm(c.to_x), Mm(c.to_y))
                shape.shadow.inherit = False
                shape.line.color.rgb = RGBColor(c.color[0], c.color[1],
                                                c.color[2])
                shape.line.width = Pt(c.linewidth)

        return prs
Exemplo n.º 5
0
    else:
        # 4:3 Aspect ration
        prs.slide_height = 6858000
        prs.slide_width = 9144000

    # Create Title Slide
    title_slide = prs.slides.add_slide(blank_slide_layout)

    # Add picture
    pic = title_slide.shapes.add_picture(images_path[h % len(images_path)], 0,
                                         0)
    pic.height = prs.slide_height
    pic.width = prs.slide_width

    # Add title
    left = Mm(20)
    top = 2130425
    width = prs.slide_width - Mm(40)
    height = Mm(60)

    title = title_slide.shapes.add_textbox(left, top, width, height)
    title.text = hymns[h][0]

    title.text_frame.word_wrap = True
    title.text_frame.paragraphs[0].alignment = PP_ALIGN.CENTER
    title.text_frame.paragraphs[0].font.size = Pt(44)
    title.text_frame.paragraphs[0].font.name = 'Arial'
    title.text_frame.paragraphs[0].font.color.rgb = text_colour

    for i in range(1, len(hymns[h])):
        # Create Blank slide
Exemplo n.º 6
0
## Build the slide
logger.info("Setting the title ")
s = prs.slides[0]
slide_shapes = s.shapes
#Update the title
title_frame = slide_shapes.title.text_frame
title_frame.clear()
new_run_in_slide(title_frame.paragraphs[0],
                 text=which_ctr + " six month view (" +
                 calendar.month_name[mm_6_before] + "-" + this_month + ")",
                 fontname="Arial",
                 fontsize=28)

#Add the one big donut showing volumes for each industry to the slide
logger.info("Adding main donut to six month view slide")
left = Mm(43)
top = Mm(48)
slide_shapes.add_picture(file_donut_ctr_ind_vols,
                         left,
                         top,
                         height=Mm(115),
                         width=Mm(94))

#Update, by centre, the top interests, and the top industries with their top interests
logger.info(
    "Setting the per-centre top 5 interests, together with per-centre top 3 industries and their interests"
)
left_pos = [Mm(180), Mm(210), Mm(240),
            Mm(270), Mm(299)]  #distances to centre of icon for each row
#First, the top interests for PA
for col, p in enumerate(kwd_counts_6m_ctr[which_ctr].most_common(5)):
Exemplo n.º 7
0
            # Used in case of slide type is Title
            # title = slide.shapes.title
            # title.text = TITLE
            continue
        #---------------------------------
        #--- Remove non-needed char.
        #---------------------------------
        s = string.replace(s, HEADER, "")  # del head of str
        s = string.replace(s, FOOTER, "")  # del tail of str
        parts = s.split(",")
        label = parts[0]
        label = string.replace(label, "\"", "")  # del double quotation
        #---------------------------------
        #--- Calc obj position in slide.
        #---------------------------------
        x = Mm(int(float(parts[1])))
        y = Mm(int(float(parts[2])))
        w = Mm(int(float(parts[3])))
        h = Mm(int(float(parts[4])))
        shape = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, x, y, w, h)
        shape.text = '%s' % label
        # print "Shape.text %s" % shape.text
        # print(shape.id, shape.text.encode('utf-8'), shape.name, shape.left, shape.top, shape.width, shape.height)

    fd.close()
    prs.save(fo)

    print("=== sysmap_pptx: End. Output file is %s" % fo)

# ----------------------------------------------
# End of File
Exemplo n.º 8
0
    def show(self, outs, shapes):
        print("show in")
        class_ids = []
        confidences = []
        boxes = []
        print(len(outs))
        for out in outs:
            print("for outs out in")
            for detection in out:
                scores = detection[5:]
                class_id = np.argmax(scores)
                confidence = scores[class_id]
                if confidence > 0.6:
                    # Object detected
                    center_x = int(detection[0] * self.width)
                    center_y = int(detection[1] * self.height)
                    w = int(detection[2] * self.width)
                    h = int(detection[3] * self.height)

                    # Rectangle coordinates
                    x = int(center_x - w / 2)
                    y = int(center_y - h / 2)

                    boxes.append([x, y, w, h])
                    confidences.append(float(confidence))
                    class_ids.append(class_id)

                    indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)

                    font = cv2.FONT_HERSHEY_PLAIN
        for i in range(len(boxes)):
            print("@@@@@@@@@@@@@@")
            print(len(boxes))
            if i in indexes:
                x, y, w, h = boxes[i]
                label = str(self.classes[class_ids[i]])
                print(label)
                try:
                    color = self.colors[i]
                except Exception as e:
                    print(e)
                #print(color)

                if label == "text":
                    print("text in")
                    #여기에 roi를 tesseract에 보내면 됨
                    #image 인식 후 텍스트 객체?
                    img = self.image
                    print(type(self.image))
                    print(",,,,,,,,,,,,,")
                    dst = img.copy()  #원본 img copy
                    print(";;;;;;;;;;;;")
                    dst = img[y + 5:y + h + 5, x - 10:x + w + 10]
                    roi = self.roi  ######################################################
                    roi = dst
                    print("_____________________")

                    #image grayscale
                    roi = cv2.cvtColor(np.asarray(roi), cv2.COLOR_BGR2GRAY)
                    roi_pil = Image.fromarray(roi)
                    roi_np = np.asarray(roi_pil)
                    s = str(i)
                    print(s)

                    #이미지 이진화 임계처리
                    blur = cv2.adaptiveThreshold(
                        roi, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                        cv2.THRESH_BINARY, 61, 13)
                    print(")))))))))))))))))))))")
                    print(type(blur))

                    array = blur - 18
                    image = Image.fromarray(array)
                    print("...............")
                    textImage = image.filter(ImageFilter.SHARPEN)  #선명함 필터 적용
                    print("filter ok")
                    textImage.save('textImage.jpg', dpi=(400, 400))  # dpi 설정
                    print("dpi save ok")

                    text = pytesseract.image_to_string(
                        textImage,
                        lang='test',
                        config='—psm 7 -c preserve_interword_spaces=1')
                    print(text)
                    text = text.replace(" ", "")  # 공백 제거
                    #text = " ".join(text.split())
                    print(text)
                    if text != "":
                        if text[0].isupper():
                            #print(text)
                            text = text.lower()
                            text = text.capitalize()  # 문장 맨 첫글자만 대문자로
                            print(text)
                        else:
                            text = text.lower()
                            print(text)
                    textBox = shapes.add_textbox(
                        Cm(x) / 50,
                        Cm(y) / 50,
                        Cm(w) / 40,
                        Cm(h) / 40)
                    text_frame = textBox.text_frame
                    text_frame.clear()
                    p = text_frame.paragraphs[0]
                    run = p.add_run()
                    run.text = text
                    font = run.font
                    real = w * h / 650
                    if real <= 15:
                        real = 20
                    font.size = Pt(real)

                    print("text out")
                    #Tesseract Text 인식 후 보정 코드

                if label == "circle":
                    print("circle in")
                    shape = shapes.add_shape(MSO_SHAPE.OVAL,
                                             Cm(x) / 50,
                                             Cm(y) / 50,
                                             Cm(w) / 50,
                                             Cm(h) / 50)
                    shape.fill.background()
                    shape.shadow.inherit = False
                    line = shape.line
                    line.color.rgb = RGBColor(0, 0, 0)
                    #line.color.brightness = 0.5
                    line.width = Mm(0.5)
                    print("circle out")

                if label == "rectangle":
                    print("rectangle in")
                    shape = shapes.add_shape(MSO_SHAPE.RECTANGLE,
                                             Cm(x) / 50,
                                             Cm(y) / 50,
                                             Cm(w) / 50,
                                             Cm(h) / 50)
                    shape.fill.background()
                    shape.shadow.inherit = False
                    line = shape.line
                    line.color.rgb = RGBColor(0, 0, 0)
                    #line.color.brightness = 0.5
                    line.width = Mm(0.5)
                    print("rectangle out")

                if label == "triangle":
                    print("triangle in")
                    shape = shapes.add_shape(MSO_SHAPE.ISOSCELES_TRIANGLE,
                                             Cm(x) / 50,
                                             Cm(y) / 50,
                                             Cm(w) / 50,
                                             Cm(h) / 50)
                    shape.fill.background()
                    shape.shadow.inherit = False
                    line = shape.line
                    line.color.rgb = RGBColor(0, 0, 0)
                    #line.color.brightness = 0.5
                    line.width = Mm(0.5)
                    print("triangle out")

                if label == "pentagon":
                    shape = shapes.add_shape(MSO_SHAPE.REGULAR_PENTAGON,
                                             Cm(x) / 85,
                                             Cm(y) / 140,
                                             Cm(w) / 180,
                                             Cm(h) / 180)
                    shape.fill.background()
                    shape.shadow.inherit = False
                    line = shape.line
                    line.color.rgb = RGBColor(0, 0, 0)
                    line.width = Mm(0.5)

                if label == "arrow1":
                    #cv2.rectangle(img, (x, y), (x + w, y + h), color, 1)

                    img = self.image  #원본 img copy
                    gray = img[y - 9:y + h + 9, x - 13:x + w + 13]
                    mask = np.zeros_like(gray)
                    mask1 = np.zeros_like(gray)
                    ret1, mask = cv2.threshold(mask, 127, 255,
                                               cv2.THRESH_BINARY_INV)
                    ret2, mask1 = cv2.threshold(mask1, 127, 255,
                                                cv2.THRESH_BINARY_INV)
                    gray = cv2.cvtColor(gray, cv2.COLOR_BGR2GRAY)
                    ret, gray = cv2.threshold(gray, 250, 255, cv2.THRESH_OTSU)
                    image_binary, contours, hierarchy = cv2.findContours(
                        gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
                    #drawContour on mask
                    cnt = sorted(contours, key=cv2.contourArea,
                                 reverse=True)[1]
                    cv2.drawContours(mask, cnt, -1, (0, 0, 0), 3)
                    #Ramer-Douglas-Peucker algorithm
                    epsilon = 0.02 * cv2.arcLength(cnt, True)
                    approx_corners = cv2.approxPolyDP(cnt, epsilon, True)
                    cv2.drawContours(mask1, approx_corners, -1, (0, 0, 0), 6)
                    approx_corners = sorted(
                        np.concatenate(approx_corners).tolist())
                    approx_corners = [
                        approx_corners[i] for i in [0, 1, 2, 3, 4, 5, 6]
                    ]
                    #무게중심
                    value_x = 0
                    value_y = 0
                    for i in approx_corners:
                        a, b = np.ravel(i)
                        value_x = value_x + a
                        value_y = value_y + b

                    centerx = value_x / 7
                    centery = value_y / 7
                    print(approx_corners)
                    print("centerx : ", centerx)
                    print("centery : ", centery)
                    #무게중심에서 가장 가까운 두 점 계산
                    min_distancex1 = 0
                    min_distancey1 = 0
                    min_distance1 = 1000000
                    for i in approx_corners:
                        a, b = np.ravel(i)
                        distance = math.sqrt(
                            math.pow((centerx - a), 2) +
                            math.pow((centery - b), 2))
                        if distance < min_distance1:
                            min_distance1 = distance
                            min_distancex1 = a
                            min_distancey1 = b

                    distance1 = np.array([min_distancex1, min_distancey1])

                    print("min_distancex1 : ", min_distancex1)
                    print("min_distancey1 : ", min_distancey1)

                    min_distancex2 = 0
                    min_distancey2 = 0
                    min_distance2 = 100000
                    for i in approx_corners:
                        a, b = np.ravel(i)
                        distance = math.sqrt(
                            math.pow((centerx - a), 2) +
                            math.pow((centery - b), 2))
                        if distance < min_distance2:
                            if a == min_distancex1 and b == min_distancey1:
                                continue
                            min_distance2 = distance
                            min_distancex2 = a
                            min_distancey2 = b

                    distance2 = np.array([min_distancex2, min_distancey2])

                    print("min_distancex2 : ", min_distancex2)
                    print("min_distancey2 : ", min_distancey2)

                    center = np.array([centerx, centery])

                    z1 = [i - j for i, j in zip(distance1, center)]
                    z2 = [i - j for i, j in zip(distance2, center)]

                    print("z1 : ", z1)
                    print("z2 : ", z2)

                    #벡터 연산
                    vector = [i + j for i, j in zip(z1, z2)]
                    a, b = np.ravel(vector)

                    print("vector : ", vector)

                    reference = np.array([1, 0])
                    vector = np.array([a, -b])

                    vector_size = math.sqrt(
                        math.pow((a), 2) + math.pow((b), 2))
                    cosinseta = np.dot(vector, reference) / vector_size
                    print("cosinseta : ", cosinseta)

                    degree = np.arccos(cosinseta)
                    degree = np.rad2deg(degree)
                    print("degree : ", degree)

                    shape = shapes.add_shape(MSO_SHAPE.RIGHT_ARROW,
                                             Cm(x) / 50,
                                             Cm(y) / 50,
                                             Cm(w) / 50,
                                             Cm(h) / 50)
                    #rotate clockwise
                    if 338 < degree and 360 > degree:
                        degree = 0
                    elif 0 < degree and 22.5 > degree:
                        degree = 0
                    elif 22.5 < degree and 67.5 > degree:
                        degree = 45
                    elif 67.5 < degree and 112.5 > degree:
                        degree = 90
                    elif 112.5 < degree and 157.5 > degree:
                        degree = 135
                    elif 157.5 < degree and 202.5 > degree:
                        degree = 180
                    elif 202.5 < degree and 247.5 > degree:
                        degree = 225
                    elif 247.5 < degree and 292.5 > degree:
                        degree = 270
                    elif 292.5 < degree and 337.5 > degree:
                        degree = 315

                    shape.rotation = degree

                    shape.fill.background()
                    shape.shadow.inherit = False
                    line = shape.line
                    line.color.rgb = RGBColor(0, 0, 0)
                    line.width = Mm(0.5)

                    s = str(i)

                    cv2.imwrite('C:/Users/Hansung/Result/1' + s + '.jpg', mask)
                    cv2.imwrite('C:/Users/Hansung/Result/2' + s + '.jpg',
                                mask1)

                #arrow 나중에 추가
                print("%%%%%%%%%%%%")
                #cv2.rectangle(img, (x, y), (x + w, y + h), (0,255,0), 2)
                print("^^^^^^^^^^^^^^^^^")

        print("for end")
        self.presentation.save('C:/Users/hansung/test.pptx')
        print("ppt save")

        #실제로는 욜로 인식 결과 창 안띄워도 됨, 나중에 삭제
        '''print("before show")
        cv2.imshow("Image", img)
        print("after show")
        cv2.waitKey(0)
        print('&&&&&')
        cv2.destroyAllWindows()
        print("after destroy")
        outs = self.net.forward(self.output_layers) # 이 부분 정확히 뭔지'''
        print("ooooook")

        #############이제 피피티 다시 전송 코드############
        return self.presentation
Exemplo n.º 9
0
    angle = np.deg2rad(angle)
    return (radius * np.cos(angle), radius * np.sin(angle))


radius = 60

width = 20
height = width

project = projects[0]

prs = Presentation()
blank_slide_layout = prs.slide_layouts[6]
slide = prs.slides.add_slide(blank_slide_layout)
xShifted, yShifted = xyCentered(0, 0, width, height)
txBox = slide.shapes.add_textbox(Mm(xShifted), Mm(yShifted), Mm(width),
                                 Mm(height))
tf = txBox.text_frame
tf.text = project

cInteractions = interactions[project]
nbrPartners = len(cInteractions)
angleIncr = 360.0 / nbrPartners
angle = 0

shapes = slide.shapes

for partner, labels in cInteractions.items():
    print(partner)
    x, y = xyByPolar(radius, angle)
    print(x, y)