Best Python code snippet using playwright-python
flatten_dict.py
Source:flatten_dict.py  
1fetty = {u'annotation': {u'authors': [{u'attribution': 0.4148936170212766,2    u'user': {u'avatar': {u'medium': {u'bounding_box': {u'height': 400,3        u'width': 300},4       u'url': u'https://images.rapgenius.com/avatars/medium/9b1f1163725586c1815090a72e8027e0'},5      u'thumb': {u'bounding_box': {u'height': 32, u'width': 32},6       u'url': u'https://images.rapgenius.com/avatars/thumb/9b1f1163725586c1815090a72e8027e0'},7      u'tiny': {u'bounding_box': {u'height': 16, u'width': 16},8       u'url': u'https://images.rapgenius.com/avatars/tiny/9b1f1163725586c1815090a72e8027e0'}},9     u'human_readable_role_for_display': u'Staff',10     u'id': 1964677,11     u'iq': 5405.35488334972,12     u'login': u'CalHx',13     u'name': u'CalHx',14     u'role_for_display': u'regulator',15     u'url': u'http://genius.com/CalHx'}},16   {u'attribution': 0.3191489361702128,17    u'user': {u'avatar': {u'medium': {u'bounding_box': {u'height': 400,18        u'width': 300},19       u'url': u'https://images.rapgenius.com/avatars/medium/57c8e3b3c5c76513f2204964f84d0118'},20      u'thumb': {u'bounding_box': {u'height': 32, u'width': 32},21       u'url': u'https://images.rapgenius.com/avatars/thumb/57c8e3b3c5c76513f2204964f84d0118'},22      u'tiny': {u'bounding_box': {u'height': 16, u'width': 16},23       u'url': u'https://images.rapgenius.com/avatars/tiny/57c8e3b3c5c76513f2204964f84d0118'}},24     u'human_readable_role_for_display': u'Editor',25     u'id': 465645,26     u'iq': 12080.2287908188,27     u'login': u'i_like_rap_a_lot',28     u'name': u'i_like_rap_a_lot',29     u'role_for_display': u'editor',30     u'url': u'http://genius.com/i_like_rap_a_lot'}},31   {u'attribution': 0.2021276595744681,32    u'user': {u'avatar': {u'medium': {u'bounding_box': {u'height': 400,33        u'width': 300},34       u'url': u'https://images.rapgenius.com/avatars/medium/8585c721072891b3ce0dcb2a57ef9050'},35      u'thumb': {u'bounding_box': {u'height': 32, u'width': 32},36       u'url': u'https://images.rapgenius.com/avatars/thumb/8585c721072891b3ce0dcb2a57ef9050'},37      u'tiny': {u'bounding_box': {u'height': 16, u'width': 16},38       u'url': u'https://images.rapgenius.com/avatars/tiny/8585c721072891b3ce0dcb2a57ef9050'}},39     u'human_readable_role_for_display': None,40     u'id': 1453021,41     u'iq': 35300.0792610798,42     u'login': u'YAboykiniky',43     u'name': u'YABOYNICKY',44     u'role_for_display': None,45     u'url': u'http://genius.com/YAboykiniky'}},46   {u'attribution': 0.05319148936170213,47    u'user': {u'avatar': {u'medium': {u'bounding_box': {u'height': 400,48        u'width': 300},49       u'url': u'https://images.rapgenius.com/avatars/medium/79a00299f87f0526b3fa30dc5a7ea7b0'},50      u'thumb': {u'bounding_box': {u'height': 32, u'width': 32},51       u'url': u'https://images.rapgenius.com/avatars/thumb/79a00299f87f0526b3fa30dc5a7ea7b0'},52      u'tiny': {u'bounding_box': {u'height': 16, u'width': 16},53       u'url': u'https://images.rapgenius.com/avatars/tiny/79a00299f87f0526b3fa30dc5a7ea7b0'}},54     u'human_readable_role_for_display': None,55     u'id': 1758473,56     u'iq': 365.393617427171,57     u'login': u'ITeachYa',58     u'name': u'ITeachYa',59     u'role_for_display': None,60     u'url': u'http://genius.com/ITeachYa'}},61   {u'attribution': 0.010638297872340425,62    u'user': {u'avatar': {u'medium': {u'bounding_box': {u'height': 400,63        u'width': 300},64       u'url': u'https://images.rapgenius.com/avatars/medium/fae65fdb981acb4255e2a7c9e9f4202e'},65      u'thumb': {u'bounding_box': {u'height': 32, u'width': 32},66       u'url': u'https://images.rapgenius.com/avatars/thumb/fae65fdb981acb4255e2a7c9e9f4202e'},67      u'tiny': {u'bounding_box': {u'height': 16, u'width': 16},68       u'url': u'https://images.rapgenius.com/avatars/tiny/fae65fdb981acb4255e2a7c9e9f4202e'}},69     u'human_readable_role_for_display': u'Staff',70     u'id': 343483,71     u'iq': 9341.4684630282,72     u'login': u'oppi',73     u'name': u'Oppi',74     u'role_for_display': u'regulator',75     u'url': u'http://genius.com/oppi'}}],76  u'body': {u'dom': {u'children': [{u'children': [u'Fetty enjoys how his girl watches him. It comforts him to know that she admires him from afar.'],77      u'tag': u'p'},78     u'',79     {u'children': [{u'attributes': {u'alt': u'',80         u'height': 227,81         u'src': u'https://images.rapgenius.com/d971f79ad1bf0105ee749eff5fe486dd.500x227x23.gif',82         u'width': 500},83        u'data': {u'animated': u'true',84         u'thumbnail': {u'height': 136,85          u'src': u'https://images.rapgenius.com/d971f79ad1bf0105ee749eff5fe486dd.300x136x1.jpg',86          u'width': 300}},87        u'tag': u'img'}],88      u'tag': u'p'},89     u'',90     {u'children': [u'Fetty instructs his girl on how they can get further acquainted\u2014he wants her to come closer.'],91      u'tag': u'p'},92     u'',93     {u'children': [u'Fetty fans should be familiar with this request \u2014he says it in his smash hit\xa0',94       {u'attributes': {u'href': u'http://genius.com/mecha/Fetty-wap-my-way-lyrics'},95        u'children': [u'\u201cMy Way.\u201d'],96        u'data': {u'api_path': u'/songs/653082'},97        u'tag': u'a'}],98      u'tag': u'p'},99     u'',100     {u'children': [{u'children': [{u'attributes': {u'href': u'http://genius.com/4831186'},101          u'children': [u'Baby, won\u2019t you come my way?'],102          u'data': {u'api_path': u'/referents/4831186'},103          u'tag': u'a'}],104        u'tag': u'p'}],105      u'tag': u'blockquote'}],106    u'tag': u'root'}},107  u'comment_count': 0,108  u'community': True,109  u'cosigned_by': [],110  u'current_user_metadata': {u'interactions': {u'cosign': False,111    u'pyong': False,112    u'vote': None},113   u'permissions': [u'create_comment']},114  u'id': 8426730,115  u'pinned': False,116  u'share_url': u'http://genius.com/8426730',117  u'state': u'accepted',118  u'url': u'http://genius.com/8426730/Kid-ink-promise/I-love-the-way-you-stare-at-me-when-you-look-my-way-this-is-something-you-should-hear-baby-would-you-come-my-way',119  u'verified': False,120  u'verified_by': None,121  u'votes_total': 6},122 u'referent': {u'annotatable': {u'api_path': u'/songs/2396122',123   u'client_timestamps': {u'lyrics_updated_at': 1456519684,124    u'updated_by_human_at': 1458080352},125   u'id': 2396122,126   u'link_title': u'Promise by\xa0Kid\xa0Ink (Ft.\xa0Fetty\xa0Wap)',127   u'title': u'Promise',128   u'type': u'Song',129   u'url': u'http://genius.com/Kid-ink-promise-lyrics'},130  u'annotator_id': 1453021,131  u'annotator_login': u'YAboykiniky',132  u'api_path': u'/referents/8426730',133  u'classification': u'accepted',134  u'fragment': u'I love the way you stare\n At me when you look my way\n This is something you should hear\n Baby would you come my way',135  u'id': 8426730,136  u'is_description': False,137  u'path': u'/8426730/Kid-ink-promise/I-love-the-way-you-stare-at-me-when-you-look-my-way-this-is-something-you-should-hear-baby-would-you-come-my-way',138  u'range': {u'content': u'I love the way you stare\n At me when you look my way\n This is something you should hear\n Baby would you come my way'},139  u'song_id': 2396122,140  u'url': u'http://genius.com/8426730/Kid-ink-promise/I-love-the-way-you-stare-at-me-when-you-look-my-way-this-is-something-you-should-hear-baby-would-you-come-my-way',141  u'verified_annotator_ids': []}}142ex = {143    "name": {144        "first": "One",145        "last": "Drone"146    },147    "job": "scout",148    "recent": {},149    "additional": {150        "place": {151            "zone": "1",152            "cell": "2"}153    }154}155ex2 = {"job":{"1":"scout","2":"worker","3":"writer","4":"reader","5":"learner"},"name":{"nick":{},"last":"Drone","first":"Second"},"recent":{"places":{"earth":{"NP":"","NY":"2017","Louvre":"2015"}},"times":{"XXI":{"2064":"Nope"},"XX":{"1964":"Yes"}}}}156name = {"name":157    {"nick":{},158    "last":"Drone",159    "first":"Second"}}160my_way_annotation = {u'authors': [{u'attribution': 0.4148936170212766,161   u'user': {u'avatar': {u'medium': {u'bounding_box': {u'height': 400,162       u'width': 300},163      u'url': u'https://images.rapgenius.com/avatars/medium/9b1f1163725586c1815090a72e8027e0'},164     u'thumb': {u'bounding_box': {u'height': 32, u'width': 32},165      u'url': u'https://images.rapgenius.com/avatars/thumb/9b1f1163725586c1815090a72e8027e0'},166     u'tiny': {u'bounding_box': {u'height': 16, u'width': 16},167      u'url': u'https://images.rapgenius.com/avatars/tiny/9b1f1163725586c1815090a72e8027e0'}},168    u'human_readable_role_for_display': u'Staff',169    u'id': 1964677,170    u'iq': 5405.35488334972,171    u'login': u'CalHx',172    u'name': u'CalHx',173    u'role_for_display': u'regulator',174    u'url': u'http://genius.com/CalHx'}},175  {u'attribution': 0.3191489361702128,176   u'user': {u'avatar': {u'medium': {u'bounding_box': {u'height': 400,177       u'width': 300},178      u'url': u'https://images.rapgenius.com/avatars/medium/57c8e3b3c5c76513f2204964f84d0118'},179     u'thumb': {u'bounding_box': {u'height': 32, u'width': 32},180      u'url': u'https://images.rapgenius.com/avatars/thumb/57c8e3b3c5c76513f2204964f84d0118'},181     u'tiny': {u'bounding_box': {u'height': 16, u'width': 16},182      u'url': u'https://images.rapgenius.com/avatars/tiny/57c8e3b3c5c76513f2204964f84d0118'}},183    u'human_readable_role_for_display': u'Editor',184    u'id': 465645,185    u'iq': 12080.2287908188,186    u'login': u'i_like_rap_a_lot',187    u'name': u'i_like_rap_a_lot',188    u'role_for_display': u'editor',189    u'url': u'http://genius.com/i_like_rap_a_lot'}},190  {u'attribution': 0.2021276595744681,191   u'user': {u'avatar': {u'medium': {u'bounding_box': {u'height': 400,192       u'width': 300},193      u'url': u'https://images.rapgenius.com/avatars/medium/8585c721072891b3ce0dcb2a57ef9050'},194     u'thumb': {u'bounding_box': {u'height': 32, u'width': 32},195      u'url': u'https://images.rapgenius.com/avatars/thumb/8585c721072891b3ce0dcb2a57ef9050'},196     u'tiny': {u'bounding_box': {u'height': 16, u'width': 16},197      u'url': u'https://images.rapgenius.com/avatars/tiny/8585c721072891b3ce0dcb2a57ef9050'}},198    u'human_readable_role_for_display': None,199    u'id': 1453021,200    u'iq': 35300.0792610798,201    u'login': u'YAboykiniky',202    u'name': u'YABOYNICKY',203    u'role_for_display': None,204    u'url': u'http://genius.com/YAboykiniky'}},205  {u'attribution': 0.05319148936170213,206   u'user': {u'avatar': {u'medium': {u'bounding_box': {u'height': 400,207       u'width': 300},208      u'url': u'https://images.rapgenius.com/avatars/medium/79a00299f87f0526b3fa30dc5a7ea7b0'},209     u'thumb': {u'bounding_box': {u'height': 32, u'width': 32},210      u'url': u'https://images.rapgenius.com/avatars/thumb/79a00299f87f0526b3fa30dc5a7ea7b0'},211     u'tiny': {u'bounding_box': {u'height': 16, u'width': 16},212      u'url': u'https://images.rapgenius.com/avatars/tiny/79a00299f87f0526b3fa30dc5a7ea7b0'}},213    u'human_readable_role_for_display': None,214    u'id': 1758473,215    u'iq': 365.393617427171,216    u'login': u'ITeachYa',217    u'name': u'ITeachYa',218    u'role_for_display': None,219    u'url': u'http://genius.com/ITeachYa'}},220  {u'attribution': 0.010638297872340425,221   u'user': {u'avatar': {u'medium': {u'bounding_box': {u'height': 400,222       u'width': 300},223      u'url': u'https://images.rapgenius.com/avatars/medium/fae65fdb981acb4255e2a7c9e9f4202e'},224     u'thumb': {u'bounding_box': {u'height': 32, u'width': 32},225      u'url': u'https://images.rapgenius.com/avatars/thumb/fae65fdb981acb4255e2a7c9e9f4202e'},226     u'tiny': {u'bounding_box': {u'height': 16, u'width': 16},227      u'url': u'https://images.rapgenius.com/avatars/tiny/fae65fdb981acb4255e2a7c9e9f4202e'}},228    u'human_readable_role_for_display': u'Staff',229    u'id': 343483,230    u'iq': 9341.4684630282,231    u'login': u'oppi',232    u'name': u'Oppi',233    u'role_for_display': u'regulator',234    u'url': u'http://genius.com/oppi'}}],235 u'body': {u'dom': {u'children': [{u'children': [u'Fetty enjoys how his girl watches him. It comforts him to know that she admires him from afar.'],236     u'tag': u'p'},237    u'',238    {u'children': [{u'attributes': {u'alt': u'',239        u'height': 227,240        u'src': u'https://images.rapgenius.com/d971f79ad1bf0105ee749eff5fe486dd.500x227x23.gif',241        u'width': 500},242       u'data': {u'animated': u'true',243        u'thumbnail': {u'height': 136,244         u'src': u'https://images.rapgenius.com/d971f79ad1bf0105ee749eff5fe486dd.300x136x1.jpg',245         u'width': 300}},246       u'tag': u'img'}],247     u'tag': u'p'},248    u'',249    {u'children': [u'Fetty instructs his girl on how they can get further acquainted\u2014he wants her to come closer.'],250     u'tag': u'p'},251    u'',252    {u'children': [u'Fetty fans should be familiar with this request \u2014he says it in his smash hit\xa0',253      {u'attributes': {u'href': u'http://genius.com/mecha/Fetty-wap-my-way-lyrics'},254       u'children': [u'\u201cMy Way.\u201d'],255       u'data': {u'api_path': u'/songs/653082'},256       u'tag': u'a'}],257     u'tag': u'p'},258    u'',259    {u'children': [{u'children': [{u'attributes': {u'href': u'http://genius.com/4831186'},260         u'children': [u'Baby, won\u2019t you come my way?'],261         u'data': {u'api_path': u'/referents/4831186'},262         u'tag': u'a'}],263       u'tag': u'p'}],264     u'tag': u'blockquote'}],265   u'tag': u'root'}},266 u'comment_count': 0,267 u'community': True,268 u'cosigned_by': [],269 u'current_user_metadata': {u'interactions': {u'cosign': False,270   u'pyong': False,271   u'vote': None},272  u'permissions': [u'create_comment']},273 u'id': 8426730,274 u'pinned': False,275 u'share_url': u'http://genius.com/8426730',276 u'state': u'accepted',277 u'url': u'http://genius.com/8426730/Kid-ink-promise/I-love-the-way-you-stare-at-me-when-you-look-my-way-this-is-something-you-should-hear-baby-would-you-come-my-way',278 u'verified': False,279 u'verified_by': None,280 u'votes_total': 6}281def flatten(dictionary):282    stack = [((), dictionary)]283    result = {}284    while stack:285        path, current = stack.pop()286        for k, v in current.items():287            if isinstance(v, dict):288                if v:289                    stack.append((path + (k,), v))290                else:291                    result["/".join((path + (k,)))] = ""292            else:293                result["/".join((path + (k,)))] = v294    return result295# flatten(ex)296# print flatten(name)297flattened = flatten(my_way_annotation)298for k, v in flattened.iteritems():...shape_factory.py
Source:shape_factory.py  
1"""2Copyright (c) 2013, Cogniteam3All rights reserved.4Redistribution and use in source and binary forms, with or without5modification, are permitted provided that the following conditions are met:6 *  Redistributions of source code must retain the above copyright7    notice, this list of conditions and the following disclaimer.8 *  Redistributions in binary form must reproduce the above copyright9    notice, this list of conditions and the following disclaimer in the10    documentation and/or other materials provided with the distribution.11 *  Neither the name of the Cogniteam nor the12    names of its contributors may be used to endorse or promote products13    derived from this software without specific prior written permission.14THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND15ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED16WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE17DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY18DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES19(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;20LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND21ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT22(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS23SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.24"""25from __future__ import division26from python_qt_binding.QtCore import Qt, QPointF27from python_qt_binding.QtGui import QBrush, QGraphicsEllipseItem, QGraphicsRectItem, QGraphicsSimpleTextItem, \28                                    QPainterPath, QPen, QGraphicsPolygonItem, QPolygonF29class StaticClassError(Exception):30    pass31class QGraphicsRoundRectItem(QGraphicsRectItem):32    def __init__(self, bounding_box):33        super(QGraphicsRoundRectItem, self).__init__(bounding_box)34    def paint(self, painter, option, widget):35        if self.pen() is not None:36            painter.setPen(self.pen())37        painter.drawRoundedRect(self.boundingRect(), 4.0, 4.0)38class ShapeFactory:39    message = None40    def __init__(self):41        raise StaticClassError("%s is a static class and cannot be initiated." % ShapeFactory)42    @staticmethod43    def create(shape, bounding_box):44        ShapeFactory.message = None45        graphics_item = None46        if shape in ('box', 'rect', 'rectangle'):47            graphics_item = QGraphicsRoundRectItem(bounding_box)48        elif shape in ('ellipse', 'point'):49            graphics_item = QGraphicsEllipseItem(bounding_box)50        elif shape == 'diamond':51            points = QPolygonF([QPointF(bounding_box.x(),52                                        bounding_box.y() + bounding_box.height() / 2),53                                QPointF(bounding_box.x() + bounding_box.width() / 2,54                                        bounding_box.y() + bounding_box.height()),55                                QPointF(bounding_box.x() + bounding_box.width(),56                                        bounding_box.y() + bounding_box.height() / 2),57                                QPointF(bounding_box.x() + bounding_box.width() / 2,58                                        bounding_box.y())])59            graphics_item = QGraphicsPolygonItem(points)60        elif shape == 'parallelogram':61            points = QPolygonF([QPointF(bounding_box.x() + bounding_box.width() * 1/6,62                                        bounding_box.y()),63                                QPointF(bounding_box.x() + bounding_box.width(),64                                        bounding_box.y()),65                                QPointF(bounding_box.x() + bounding_box.width() * 5/6,66                                        bounding_box.y() + bounding_box.height()),67                                QPointF(bounding_box.x(),68                                        bounding_box.y() + bounding_box.height())])69            graphics_item = QGraphicsPolygonItem(points)70        elif shape == 'cds':71            points = QPolygonF([QPointF(bounding_box.x(),72                                        bounding_box.y()),73                                QPointF(bounding_box.x() + bounding_box.width() * 5/6,74                                        bounding_box.y()),75                                QPointF(bounding_box.x() + bounding_box.width(),76                                        bounding_box.y() + bounding_box.height() / 2),77                                QPointF(bounding_box.x() + bounding_box.width() * 5/6,78                                        bounding_box.y() + bounding_box.height()),79                                QPointF(bounding_box.x(),80                                        bounding_box.y() + bounding_box.height())])81            graphics_item = QGraphicsPolygonItem(points)82        elif shape == 'rarrow':83            points = QPolygonF([QPointF(bounding_box.x(),84                                        bounding_box.y()),85                                QPointF(bounding_box.x() + bounding_box.width() * 4/6,86                                        bounding_box.y()),87                                QPointF(bounding_box.x() + bounding_box.width() * 4/6,88                                        bounding_box.y() - bounding_box.height() * 2/6),89                                QPointF(bounding_box.x() + bounding_box.width(),90                                        bounding_box.y() + bounding_box.height() / 2),91                                QPointF(bounding_box.x() + bounding_box.width() * 4/6,92                                        bounding_box.y() + bounding_box.height() * 8/6),93                                QPointF(bounding_box.x() + bounding_box.width() * 4/6,94                                        bounding_box.y() + bounding_box.height()),95                                QPointF(bounding_box.x(),96                                        bounding_box.y() + bounding_box.height())])97            graphics_item = QGraphicsPolygonItem(points)98        elif shape == 'larrow':99            points = QPolygonF([QPointF(bounding_box.x() + bounding_box.width() * 2/6,100                                        bounding_box.y()),101                                QPointF(bounding_box.x() + bounding_box.width() * 2/6,102                                        bounding_box.y() - bounding_box.height() * 2/6),103                                QPointF(bounding_box.x(),104                                        bounding_box.y() + bounding_box.height() / 2),105                                QPointF(bounding_box.x() + bounding_box.width() * 2/6,106                                        bounding_box.y() + bounding_box.height() * 8/6),107                                QPointF(bounding_box.x() + bounding_box.width() * 2/6,108                                        bounding_box.y() + bounding_box.height()),109                                QPointF(bounding_box.x() + bounding_box.width(),110                                        bounding_box.y() + bounding_box.height()),111                                QPointF(bounding_box.x() + bounding_box.width(),112                                        bounding_box.y())])113            graphics_item = QGraphicsPolygonItem(points)114        elif shape == 'record':115            graphics_item = QGraphicsRectItem(bounding_box)116        elif shape == 'hexagon':117            points = QPolygonF([QPointF(bounding_box.x() + bounding_box.width() * 1/5,118                                        bounding_box.y()),119                                QPointF(bounding_box.x() + bounding_box.width() * 4/5,120                                        bounding_box.y()),121                                QPointF(bounding_box.x() + bounding_box.width(),122                                        bounding_box.y() + bounding_box.height() / 2),123                                QPointF(bounding_box.x() + bounding_box.width() * 4/5,124                                        bounding_box.y() + bounding_box.height()),125                                QPointF(bounding_box.x() + bounding_box.width() * 1/5,126                                        bounding_box.y() + bounding_box.height()),127                                QPointF(bounding_box.x(),128                                        bounding_box.y() + bounding_box.height() / 2)])129            graphics_item = QGraphicsPolygonItem(points)130        elif shape == 'triangle':131            points = QPolygonF([QPointF(bounding_box.x() + bounding_box.width() / 2,132                                        bounding_box.y()),133                                QPointF(bounding_box.x() + bounding_box.width(),134                                        bounding_box.y() + bounding_box.height() * 3/4),135                                QPointF(bounding_box.x(),136                                        bounding_box.y() + bounding_box.height() * 3/4)])137            graphics_item = QGraphicsPolygonItem(points)138        elif shape == 'circle':139            diameter = min(bounding_box.width(), bounding_box.height())140            graphics_item = QGraphicsEllipseItem(bounding_box.x(), bounding_box.y(), diameter, diameter)141        else:142            graphics_item = QGraphicsRectItem(bounding_box)143            ShapeFactory.message = "WARNING: %s is unknown shape, box used instead" % shape...postprocess.py
Source:postprocess.py  
1import torch2import cv23import numpy as np4import torch.nn as nn5def mask_filter(pixel_mask, link_mask, neighbors=8, scale=4):6    """7    pixel_mask: batch_size * 2 * H * W8    link_mask: batch_size * 16 * H * W9    """10    batch_size = link_mask.size(0)11    mask_height = link_mask.size(2)12    mask_width = link_mask.size(3)13    pixel_class = nn.Softmax2d()(pixel_mask)14    # print(pixel_class.shape)15    pixel_class = pixel_class[:, 1] > 0.716    # print(pixel_class.shape)17    # pixel_class = pixel_mask[:, 1] > pixel_mask[:, 0]18    # link_neighbors = torch.ByteTensor([batch_size, neighbors, mask_height, mask_width])19    link_neighbors = torch.zeros([batch_size, neighbors, mask_height, mask_width], dtype=torch.uint8, device=pixel_mask.device)20    21    for i in range(neighbors):22        # print(link_mask[:, [2 * i, 2 * i + 1]].shape)23        tmp = nn.Softmax2d()(link_mask[:, [2 * i, 2 * i + 1]])24        # print(tmp.shape)25        link_neighbors[:, i] = tmp[:, 1] > 0.726        # link_neighbors[:, i] = link_mask[:, 2 * i + 1] > link_mask[:, 2 * i] 27        link_neighbors[:, i] = link_neighbors[:, i] & pixel_class28    # res_mask = np.zeros([batch_size, mask_height, mask_width], dtype=np.uint8)29    pixel_class = pixel_class.cpu().numpy()30    link_neighbors = link_neighbors.cpu().numpy()31    return pixel_class, link_neighbors32def mask_to_box(pixel_mask, link_mask, neighbors=8, scale=4):33    """34    pixel_mask: batch_size * 2 * H * W35    link_mask: batch_size * 16 * H * W36    """37    def distance(a, b):38        return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 239    def short_side_filter(bounding_box):40        for i, point in enumerate(bounding_box):41            if distance(point, bounding_box[(i+1)%4]) < 5**2:42                return True # ignore it43        return False # do not ignore44    batch_size = link_mask.size(0)45    mask_height = link_mask.size(2)46    mask_width = link_mask.size(3)47    pixel_class = nn.Softmax2d()(pixel_mask)48    # print(pixel_class.shape)49    pixel_class = pixel_class[:, 1] > 0.750    # pixel_class = pixel_mask[:, 1] > pixel_mask[:, 0]51    # link_neighbors = torch.ByteTensor([batch_size, neighbors, mask_height, mask_width])52    link_neighbors = torch.zeros([batch_size, neighbors, mask_height, mask_width], dtype=torch.uint8, device=pixel_mask.device)53    54    for i in range(neighbors):55        # print(link_mask[:, [2 * i, 2 * i + 1]].shape)56        tmp = nn.Softmax2d()(link_mask[:, [2 * i, 2 * i + 1]])57        # print(tmp.shape)58        link_neighbors[:, i] = tmp[:, 1] > 0.759        # link_neighbors[:, i] = link_mask[:, 2 * i + 1] > link_mask[:, 2 * i] 60        link_neighbors[:, i] = link_neighbors[:, i] & pixel_class61    # res_mask = np.zeros([batch_size, mask_height, mask_width], dtype=np.uint8)62    all_boxes = []63    # res_masks = []64    for i in range(batch_size):65        res_mask = func(pixel_class[i], link_neighbors[i])66        box_num = np.amax(res_mask)67        # print(res_mask.any())68        bounding_boxes = []69        for i in range(1, box_num + 1):70            box_mask = (res_mask == i).astype(np.uint8)71            # res_masks.append(box_mask)72            if box_mask.sum() < 100:73                pass74                # print("<150")75                # continue76            box_mask, contours, _ = cv2.findContours(box_mask, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)77            # print(contours[0])78            bounding_box = cv2.minAreaRect(contours[0])79            bounding_box = cv2.boxPoints(bounding_box)80            if short_side_filter(bounding_box):81                # print("<5")82                pass83                continue84            # bounding_box = bounding_box.reshape(8)85            bounding_box = np.clip(bounding_box * scale, 0, 128 * scale - 1).astype(np.int)86            # import IPython87            # IPython.embed()88            bounding_boxes.append(bounding_box)89        all_boxes.append(bounding_boxes)90    return all_boxes91def get_neighbors(h_index, w_index):92    res = []93    res.append((h_index - 1, w_index - 1))94    res.append((h_index - 1, w_index))95    res.append((h_index - 1, w_index + 1))96    res.append((h_index, w_index + 1))97    res.append((h_index + 1, w_index + 1))98    res.append((h_index + 1, w_index))99    res.append((h_index + 1, w_index - 1))100    res.append((h_index, w_index - 1))101    return res102def func(pixel_cls, link_cls):103    def joint(pointa, pointb):104        roota = find_root(pointa)105        rootb = find_root(pointb)106        if roota != rootb:107            group_mask[rootb] = roota108            # group_mask[pointb] = roota109            # group_mask[pointa] = roota110        return111    def find_root(pointa):112        root = pointa113        while group_mask.get(root) != -1:114            root = group_mask.get(root)115        return root116    pixel_cls = pixel_cls.cpu().numpy()117    link_cls = link_cls.cpu().numpy()118    # import IPython119    # IPython.embed()120    # print(pixel_cls.any())121    # print(np.where(pixel_cls))122    pixel_points = list(zip(*np.where(pixel_cls)))123    h, w = pixel_cls.shape124    group_mask = dict.fromkeys(pixel_points, -1)125    # print(group_mask)126    for point in pixel_points:127        h_index, w_index = point128        # print(point)129        neighbors = get_neighbors(h_index, w_index)130        for i, neighbor in enumerate(neighbors):131            nh_index, nw_index = neighbor132            if nh_index < 0 or nw_index < 0 or nh_index >= h or nw_index >= w:133                continue134            if pixel_cls[nh_index, nw_index] == 1 and link_cls[i, h_index, w_index] == 1:135                joint(point, neighbor)136    res = np.zeros(pixel_cls.shape, dtype=np.uint8)137    root_map = {}138    for point in pixel_points:139        h_index, w_index = point140        root = find_root(point)141        if root not in root_map:142            root_map[root] = len(root_map) + 1143        res[h_index, w_index] = root_map[root]144    return res145if __name__ == '__main__':146    # file_path = r'/data/shentao/Airbus/code/models/model34_DeepSupervised_resize384/samples/37_1500_output.png'147    # img = cv2.imread(file_path, 0)148    # print(img.shape)149    #150    # for i in range(30,100):151    #     # i = 14152    #     img_tmp = img[i*384:(i+1)*384, 384:]153    #     print(img_tmp.shape)154    #155    #     cv2.imwrite('tmp.png', img_tmp)156    #157    #     file_path = r'tmp.png'158    #     img_tmp = cv2.imread(file_path, 0)159    #     box_mask, contours, _ = cv2.findContours(img_tmp, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)160    #     print(len(contours))161    #162    #     if len(contours) > 3:163    #         break164    file_path = r'tmp.png'165    img_tmp = cv2.imread(file_path, 0)166    box_mask, contours, _ = cv2.findContours(img_tmp, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)167    print(len(contours))168    for i in range(len(contours)):169        bounding_box = cv2.minAreaRect(contours[i])170        bounding_box = cv2.boxPoints(bounding_box)171        bounding_box = np.array(bounding_box, dtype=np.int32)172        bounding_box = bounding_box.reshape([1,bounding_box.shape[0],bounding_box.shape[1]])173        print(bounding_box.shape)174        cv2.fillPoly(img_tmp, bounding_box, 255)175        # print(bounding_box)176        # cv2.line(img_tmp, (int(bounding_box[0][0]),int(bounding_box[0][1])), (int(bounding_box[1][0]),int(bounding_box[1][1])), 255, 2)177        # cv2.line(img_tmp, (int(bounding_box[1][0]), int(bounding_box[1][1])),(int(bounding_box[2][0]), int(bounding_box[2][1])), 255, 2)178        # cv2.line(img_tmp, (int(bounding_box[2][0]), int(bounding_box[2][1])),(int(bounding_box[3][0]), int(bounding_box[3][1])), 255, 2)179        # cv2.line(img_tmp, (int(bounding_box[3][0]), int(bounding_box[3][1])),(int(bounding_box[0][0]), int(bounding_box[0][1])), 255, 2)180    cv2.imwrite('tmp_bbox.png', img_tmp)181    # cv2.floodFill(img_tmp, img_tmp, (0, 0), 255)182    # cv2.imwrite('tmp_bbox_fill.png', img_tmp)183    a = np.array([[[10, 10], [100, 10], [100, 100], [10, 100]]], dtype=np.int32)...quickstart.py
Source:quickstart.py  
1#!/usr/bin/env python2# Copyright 2016 Google Inc. All Rights Reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8#     http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15# [START vision_quickstart]16import io17import os18import sys19import copy20# import socket21# import requests22# import socks23# Imports the Google Cloud client library24# [START vision_python_migration_import]25from google.cloud import vision26from google.cloud.vision import types27# [END vision_python_migration_import]28import translate as trans29import drawline as draw30import infostruct as ifs31def sizefilter(vertices, v):32    minx = 99999999933    miny = 99999999934    maxx = -135    maxy = -136    for vertex in vertices:37        if vertex.x < minx:38            minx = vertex.x39        if vertex.x > maxx:40            maxx = vertex.x41        if vertex.y < miny:42            miny = vertex.y43        if vertex.y > maxy:44            maxy = vertex.y45    if ((maxx - minx < v) or (maxy - miny < v)):46        return True47    return False48def expand(vertices, v):49    t_vertices = copy.deepcopy(vertices)50    t_vertices[0].x = t_vertices[0].x - v51    t_vertices[1].x = t_vertices[1].x + v52    t_vertices[2].x = t_vertices[2].x + v53    t_vertices[3].x = t_vertices[3].x - v54    t_vertices[0].y = t_vertices[0].y - v55    t_vertices[1].y = t_vertices[1].y - v56    t_vertices[2].y = t_vertices[2].y + v57    t_vertices[3].y = t_vertices[3].y + v58    return t_vertices59def gettingdir(vertices):60    minx = 99999999961    miny = 99999999962    maxx = -163    maxy = -164    for vertex in vertices:65        if vertex.x < minx:66            minx = vertex.x67        if vertex.x > maxx:68            maxx = vertex.x69        if vertex.y < miny:70            miny = vertex.y71        if vertex.y > maxy:72            maxy = vertex.y73    dx = maxx - minx74    dy = maxy - miny75    if (dx <= dy):76        return 177    return 078def run_quickstart(file_name):79    ret = []80    # Instantiates a client81    # [START vision_python_migration_client]82    client = vision.ImageAnnotatorClient()83    # [END vision_python_migration_client]84    # The name of the image file to annotate85    # file_name = os.path.join(os.path.dirname(__file__),'t3.jpg')86    # file_name = os.path.join('/root/pic/', 't3.jpg')87    # Loads the image into memory88    with io.open(file_name, 'rb') as image_file:89        content = image_file.read()90    image = vision.types.Image(content=content)91    # Performs label detection on the image file92    response = client.document_text_detection(image=image)93    blocki = 094    infoc = 195    for page in response.full_text_annotation.pages:96        for block in page.blocks:97            if (block.block_type != 1):98                continue99            if sizefilter(block.bounding_box.vertices, 20):100                continue101            # print('{}\n'.format(block.confidence))102            # print('{}\n'.format(block.block_type))103            # f.write('\nBlock confidence: {}\n'.format(block.confidence))104            blocki = blocki + 1105            # f.write('Block # {} :\n'.format(blocki))106            vertices = (['({},{})'.format(vertex.x, vertex.y) for vertex in block.bounding_box.vertices])107            # f.write('bounds: {} \n'.format(','.join(vertices)))108            # block.bounding_box.vertices[1].x109            '''110            draw.drawline((block.bounding_box.vertices[0].x, block.bounding_box.vertices[0].y), (block.bounding_box.vertices[1].x, block.bounding_box.vertices[1].y), (0, 255, 0))111            draw.drawline((block.bounding_box.vertices[1].x, block.bounding_box.vertices[1].y), (block.bounding_box.vertices[2].x, block.bounding_box.vertices[2].y), (0, 255, 0))112            draw.drawline((block.bounding_box.vertices[2].x, block.bounding_box.vertices[2].y), (block.bounding_box.vertices[3].x, block.bounding_box.vertices[3].y), (0, 255, 0))113            draw.drawline((block.bounding_box.vertices[3].x, block.bounding_box.vertices[3].y), (block.bounding_box.vertices[0].x, block.bounding_box.vertices[0].y), (0, 255, 0))114            '''115            tbound = expand(block.bounding_box.vertices, 20)116            '''117            draw.drawline((tbound[0].x, tbound[0].y), (tbound[1].x, tbound[1].y), (0, 255, 0))118            draw.drawline((tbound[1].x, tbound[1].y), (tbound[2].x, tbound[2].y), (0, 255, 0))119            draw.drawline((tbound[2].x, tbound[2].y), (tbound[3].x, tbound[3].y), (0, 255, 0))120            draw.drawline((tbound[3].x, tbound[3].y), (tbound[0].x, tbound[0].y), (0, 255, 0))121            '''122            for paragraph in block.paragraphs:123                # f.write('Paragraph confidence: {}'.format(124                #    paragraph.confidence))125                centence = ''126                for word in paragraph.words:127                    if sizefilter(word.bounding_box.vertices, 20):128                        continue129                    vertices = (['({},{})'.format(vertex.x, vertex.y) for vertex in word.bounding_box.vertices])130                    word_text = ''.join([symbol.text for symbol in word.symbols])131                    # f.write('Word text: {} '.format(word_text))132                    # f.write('bounds: {} \n'.format(','.join(vertices)))133                    centence = centence + word_text134                ifb = ifs.Info()135                ifb.id = infoc136                infoc = infoc + 1137                vet = []138                for vertex in paragraph.bounding_box.vertices:139                    vet.append([vertex.x, vertex.y])140                ifb.vertexs = vet141                ifb.direct = gettingdir(paragraph.bounding_box.vertices)142                # f.write('centence : {}\n'.format(centence))143                ifb.text = centence144                transans = trans.ask_translation('ja', centence)145                ifb.trans = transans146                # f.write('translation : {}\n'.format(transans))147                ifb.showInfo()148                ret.append(ifb)149    return ret150def drawShow(infile, outfile, infos):151    draw.openpic(infile)152    for item in infos:153        if (item.enable != 1):154            continue155        b = item.vertexs156        draw.drawline((b[0][0], b[0][1]), (b[1][0], b[1][1]), (0, 255, 0))157        draw.drawline((b[1][0], b[1][1]), (b[2][0], b[2][1]), (0, 255, 0))158        draw.drawline((b[2][0], b[2][1]), (b[3][0], b[3][1]), (0, 255, 0))159        draw.drawline((b[3][0], b[3][1]), (b[0][0], b[0][1]), (0, 255, 0))160    draw.writepic(outfile)161if __name__ == '__main__':162    f = open('ans.txt', 'w')163    # file_name='/root/pic/t3.jpg'164    file_name = '/root/pic/' + sys.argv[1]165    draw.openpic(file_name)166    os.system("export GOOGLE_APPLICATION_CREDENTIALS=\"/root/mykey.json\"")167    rst = run_quickstart(file_name)168    draw.writepic('pro_' + sys.argv[1])...LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
