Ejemplo n.º 1
0
import lxml.etree as ET
import lxml.builder as BR
import xml.etree.ElementTree as eTree

XML_NAMESPACE = "urn:iso:std:iso:20022:tech:xsd:acmt.02z.001.01:Report"

E = BR.ElementMaker(namespace=XML_NAMESPACE,
                    nsmap={None: "urn:iso:std:iso:20022:tech:xsd:acmt.02z.001.01:Report"})

Document = E.Document
AcctSwtchngInfSvcRptV01 = E.AcctSwtchngInfSvcRptV01
Assgnmt = E.Assgnmt
MsgId = E.MsgId
CreDtTm = E.CreDtTm
Assgnr = E.Assgnr
Agt = E.Agt
FinInstnId = E.FinInstnId
BICFI = E.BICFI
Assgne = E.Assgne
Pty = E.Pty
Nm = E.Nm
Id = E.Id
OrgId = E.OrgId
Othr = E.Othr
Mod = E.Mod
AcctSwtchngRef = E.AcctSwtchngRef
AcctSwtchngId = E.AcctSwtchngId
DtOfSgntr = E.DtOfSgntr
OrgnlPtyAndAcctId = E.OrgnlPtyAndAcctId
Acct = E.Acct
IBAN = E.IBAN
Ejemplo n.º 2
0
def to_xml(point):
    e = builder.ElementMaker()
    return (e.X(str(point["x"])), e.Y(str(point["y"])), e.Z(str(point["z"])))
Ejemplo n.º 3
0
import oauth2
import simplejson

from vidscraper.decorators import provide_shortmem, parse_url, returns_unicode
from vidscraper import util
from vidscraper.errors import Error
from django.conf import settings


class VimeoError(Error):
    pass


VIMEO_API_URL = 'http://vimeo.com/api/rest/v2/'

EMaker = builder.ElementMaker()
EMBED = EMaker.embed

EMBED_WIDTH = 425
EMBED_HEIGHT = 344


def get_shortmem(url):
    shortmem = {}
    video_id = VIMEO_REGEX.match(url).groupdict()['video_id']
    url = '%s?%s' % (VIMEO_API_URL,
                     urllib.urlencode({
                         'method': 'vimeo.videos.getInfo',
                         'format': 'json',
                         'video_id': video_id
                     }))
Ejemplo n.º 4
0
except ImportError:
    from email.Utils import parsedate_tz
import lxml.builder as lb

# Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
FORMAT_RFC_822 = '%a, %d %b %Y %H:%M:%S GMT'
# Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
FORMAT_RFC_850 = '%A %d-%b-%y %H:%M:%S GMT'
# Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
FORMAT_ASC = '%a %b %d %H:%M:%S %Y'

WEBDAV_NS = "DAV:"

WEBDAV_NSMAP = {'D': WEBDAV_NS}

D = lb.ElementMaker(namespace=WEBDAV_NS, nsmap=WEBDAV_NSMAP)


def get_property_tag_list(res, *names):
    props = []
    for name in names:
        tag = get_property_tag(res, name)
        if tag is None:
            continue
        props.append(tag)
    return props


def get_property_tag(res, name):
    if name == 'resourcetype':
        if res.is_collection:
Ejemplo n.º 5
0
                 rank=rank)
        continue
    if language_code == 'no':  # T114042
        language_code = 'nb'
    add_lang(language_code, value[u"name"], value[u"localname"], rank)

add_lang(key='test', local_name='Test', eng_name='Test', rank=0)
add_lang(key='en-x-piglatin',
         local_name='Igpay Atinlay',
         eng_name='Pig Latin',
         rank=0)

# Generate the XML, for Android
NAMESPACE = 'http://schemas.android.com/tools'
TOOLS = '{%s}' % NAMESPACE
x = lb.ElementMaker(nsmap={'tools': NAMESPACE})

keys = [x.item(k) for k in lang_keys]
local_names = [x.item(k) for k in lang_local_names]
eng_names = [x.item(k) for k in lang_eng_names]

resources = x.resources(
    getattr(x, 'string-array')(*keys, name='preference_language_keys'),
    getattr(x, 'string-array')(*local_names,
                               name='preference_language_local_names'),
    getattr(x, 'string-array')(*eng_names,
                               name='preference_language_canonical_names'))
resources.set(TOOLS + 'ignore', 'MissingTranslation')

with open('languages_list.xml', 'wb') as f:
    f.write(
Ejemplo n.º 6
0
    def enveloped(self, data, cert, certcontent, signproc, tspurl, tspcred):
        tree = etree.parse(io.BytesIO(data))
        signedobj = tree.getroot()
        canonicalizedxml = self._c14n(signedobj, "")
        digestvalue1 = self.sha256(canonicalizedxml)

        nsmap = signedobj.nsmap.copy()
        nsmap.update({
            "xades": "http://uri.etsi.org/01903/v1.3.2#",
            "ds": "http://www.w3.org/2000/09/xmldsig#",
        })
        siXADES = builder.ElementMaker(
            namespace="http://uri.etsi.org/01903/v1.3.2#", nsmap=nsmap)
        SignedProperties = siXADES.SignedProperties

        nsmap = signedobj.nsmap.copy()
        nsmap.update({"ds": "http://www.w3.org/2000/09/xmldsig#"})
        siDS = builder.ElementMaker(
            namespace="http://www.w3.org/2000/09/xmldsig#", nsmap=nsmap)
        SignedInfo = siDS.SignedInfo

        certdigest = self.sha256(certcontent)
        certcontent = self.base64(certcontent)
        certserialnumber = "%d" % cert.serial_number
        certissuer = self.get_rdns_name(cert.issuer.rdns)
        if self.debug:
            self.guid = "279d6285-779c-4449-9c92-6bf3f7edacc2"
            self.time = "2020-11-24T00:32:43Z"
            certissuer = "2.5.4.97=#0C10564154504C2D35313730333539343538,CN=Certum QCA 2017,O=Asseco Data Systems S.A.,C=PL"

        signedproperties = SignedProperties(
            SignedSignatureProperties(
                SigningTime(self.time),
                SigningCertificate(
                    Cert(
                        CertDigest(
                            DigestMethod(
                                Algorithm=
                                "http://www.w3.org/2001/04/xmlenc#sha256"),
                            DigestValue(certdigest),
                        ),
                        IssuerSerial(
                            X509IssuerName(certissuer),
                            X509SerialNumber(certserialnumber),
                        ),
                    )),
                Id="SignedSignatureProperties_" + self.guid + self.mapa["_02"],
            ),
            SignedDataObjectProperties(
                DataObjectFormat(
                    Description("""\
MIME-Version: 1.0
Content-Type: text/xml
Content-Transfer-Encoding: binary
Content-Disposition: filename="document.xml"\
"""),
                    ObjectIdentifier(
                        Identifier(
                            "http://www.certum.pl/OIDAsURI/signedFile/1.2.616.1.113527.3.1.1.3.1",
                            Qualifier="OIDAsURI",
                        ),
                        Description(
                            "Opis formatu dokumentu oraz jego pełna nazwa"),
                        DocumentationReferences(
                            DocumentationReference(
                                "http://www.certum.pl/OIDAsURI/signedFile.pdf")
                        ),
                    ),
                    MimeType("text/xml"),
                    ObjectReference="#Reference1_" + self.guid +
                    self.mapa["_2f"],
                ),
                Id="SignedDataObjectProperties_" + self.guid +
                self.mapa["_43"],
            ),
            Id="SignedProperties_" + self.guid + self.mapa["_46"],
        )

        canonicalizedxml = self._c14n(signedproperties, "")
        digestvalue2 = self.sha256(canonicalizedxml)
        if self.debug:
            print("*" * 20, "enveloped signedproperties")
            print(canonicalizedxml)
            print("digest:", digestvalue2)

        unsignedproperties = self.unsignedpropertied(digestvalue2, tspurl,
                                                     tspcred, "sha256")

        signedinfo = SignedInfo(
            CanonicalizationMethod(
                Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"),
            SignatureMethod(
                Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"),
            Reference(
                Transforms(
                    Transform(
                        XPath("not(ancestor-or-self::ds:Signature)"),
                        Algorithm=
                        "http://www.w3.org/TR/1999/REC-xpath-19991116",
                    )),
                DigestMethod(
                    Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"),
                DigestValue(digestvalue1),
                Id="Reference1_" + self.guid + self.mapa["_2f"],
                URI="",
            ),
            Reference(
                DigestMethod(
                    Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"),
                DigestValue(digestvalue2),
                Id="SignedProperties-Reference_" + self.guid +
                self.mapa["_20"],
                Type="http://uri.etsi.org/01903#SignedProperties",
                URI="#SignedProperties_" + self.guid + self.mapa["_46"],
            ),
            Id="SignedInfo_" + self.guid + self.mapa["_49"],
        )

        canonicalizedxml = self._c14n(signedinfo, "")
        if self.debug:
            print("*" * 20, "enveloped signedinfo")
            print(canonicalizedxml)
        signature = signproc(canonicalizedxml, "sha256")
        actualdigestencoded = base64.b64encode(signature).decode()
        digestvalue3 = []
        for i in range(0, len(actualdigestencoded), 64):
            digestvalue3.append(actualdigestencoded[i:i + 64])
        digestvalue3 = "\n".join(digestvalue3)

        DOC = Signature(
            signedinfo,
            SignatureValue(digestvalue3,
                           Id="SignatureValue_" + self.guid +
                           self.mapa["_5a"]),
            KeyInfo(
                X509Data(X509Certificate(certcontent)),
                Id="KeyInfo_" + self.guid + self.mapa["_2c"],
            ),
            Object(
                QualifyingProperties(
                    signedproperties,
                    unsignedproperties,
                    Id="QualifyingProperties_" + self.guid + self.mapa["_4b"],
                    Target="#Signature_" + self.guid + self.mapa["_11"],
                )),
            Id="Signature_" + self.guid + self.mapa["_11"],
        )

        signedobj.append(DOC)
        return tree
Ejemplo n.º 7
0
 def make_podbbang(channel_id):
     try:
         url = 'http://www.podbbang.com/ch/%s' % channel_id
         logger.debug(url)
         tree = html.fromstring(requests.get(url).content)
         tmp = builder.ElementMaker(
             nsmap={'itunes': 'http://www.itunes.com/dtds/podcast-1.0.dtd'})
         root = tmp.rss(version="2.0")
         EE = builder.ElementMaker(
             namespace="http://www.itunes.com/dtds/podcast-1.0.dtd",
             nsmap={'itunes': 'http://www.itunes.com/dtds/podcast-1.0.dtd'})
         channel_tag = (
             E.channel(
                 E.title(
                     tree.xpath('//*[@id="podcastDetails"]/div[3]/h3/text()'
                                )[0].strip()),
                 E.link(url),
                 E.description(
                     tree.xpath(
                         '//*[@id="podcastDetails"]/div[3]/div[1]/text()')
                     [0].strip()),
                 E.language('ko-kr'),
                 E.copyright(''),
                 EE.subtitle(),
                 EE.author(),
                 EE.summary(
                     tree.xpath(
                         '//*[@id="podcastDetails"]/div[3]/div[1]/text()')
                     [0].strip()),
                 EE.category(text=tree.xpath(
                     '//*[@id="podcastDetails"]/div[3]/span/a/text()')
                             [0].strip()),
                 EE.image(
                     href=tree.xpath('//*[@id="podcastDetails"]/div[3]/img')
                     [0].attrib['src']),
                 EE.explicit('no'),
                 #EE.keywords(tree.xpath('//*[@id="header_wrap"]/div/div[1]/div[2]/span/a/text()')[0].strip()),
             ))
         root.append(channel_tag)
         data = requests.get(
             'http://app-api4.podbbang.com/channel?channel=%s&order=desc&count=%s&page=1'
             % (channel_id, ModelSetting.get('pb_feed_count')),
             headers=pb_headers).json()
         for item in data['list']:
             channel_tag.append(
                 E.item(
                     E.title(item['title']), EE.subtitle(item['summary']),
                     EE.summary(item['summary']), E.guid(item['episode']),
                     E.pubDate(
                         datetime.strptime(
                             item['date'], "%Y-%m-%d %H:%M:%S").strftime(
                                 '%a, %d %b %Y %H:%M:%S') + ' +0900'),
                     EE.duration(item['duration']),
                     E.enclosure(url=item['file_url'],
                                 length=item['file_size'],
                                 type='audio/mp3'),
                     E.description(item['summary'])))
         return app.response_class(ET.tostring(root,
                                               pretty_print=True,
                                               xml_declaration=True,
                                               encoding="utf-8"),
                                   mimetype='application/xml')
     except Exception as e:
         logger.error('Exception:%s', e)
         logger.error(traceback.format_exc())
Ejemplo n.º 8
0
 def _wrapper(*args, **kwargs):
     return \
         getattr(builder.ElementMaker(makeelement=parser.makeelement),
                 name)(*args, **kwargs)
Ejemplo n.º 9
0
def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('input_dir', help='input annotated directory')
    parser.add_argument('output_dir', help='output dataset directory')
    parser.add_argument('--labels', help='labels file', required=True)
    parser.add_argument('--label_dict', help='convert label with dict')
    args = parser.parse_args()

    # make voc format directories
    if osp.exists(args.output_dir):
        print('Output directory already exists:', args.output_dir)
        sys.exit(1)
    os.makedirs(args.output_dir)
    os.makedirs(osp.join(args.output_dir, 'JPEGImages'))
    os.makedirs(osp.join(args.output_dir, 'Annotations'))
    os.makedirs(osp.join(args.output_dir, 'AnnotationsVisualization'))
    print('Creating dataset:', args.output_dir)

    # build convert dict
    if args.label_dict is not None:
        fst2snd_dict = label_name_convert_dict_build(args.label_dict)

    # get labels and save it to dataset dir
    class_names = []
    for i, line in enumerate(
            open(args.labels, 'r', encoding='UTF-8').readlines()):
        class_id = i - 1  # starts with -1
        class_name = line.strip()
        if class_id == -1:
            assert class_name == '__ignore__'
            continue
        elif class_id == 0:
            assert class_name == '_background_'

        if args.label_dict is not None:
            class_name = fst2snd_dict[class_name]
        class_names.append(class_name)
    class_names = tuple(class_names)
    print('class_names:', class_names)
    out_class_names_file = osp.join(
        args.output_dir,
        'class_names.txt')  # save labels in txt for information
    with open(out_class_names_file, 'w', encoding='UTF-8') as f:
        f.writelines('\n'.join(class_names))
    print('Saved class_names:', out_class_names_file)

    # label_file_list = glob.glob(osp.join(args.input_dir, '*.json'))
    label_file_list = os.listdir(args.input_dir)
    # for i in progressbar.progressbar(range(len(label_file_list))):
    for i in range(len(label_file_list)):
        label_file = osp.join(args.input_dir, label_file_list[i])
        print('Generating dataset from:', label_file)
        with open(label_file, 'r', encoding='UTF-8') as f:
            data = json.load(f)

        # regex: get image name
        filename = osp.splitext(osp.basename(label_file))[0]
        base = pattern.findall(
            filename
        )[0]  # TODO: you can change it here: design a method for sample name,
        # TODO: or just use file name.
        # base = osp.splitext(osp.basename(label_file))[0]

        # src image file
        out_img_file = osp.join(args.output_dir, 'JPEGImages', base + '.jpg')
        # annotation xml file
        out_xml_file = osp.join(args.output_dir, 'Annotations', base + '.xml')
        # visualize image file
        out_viz_file = osp.join(args.output_dir, 'AnnotationsVisualization',
                                base + '.jpg')
        # color annotated image file
        out_colorize_file = osp.join(args.output_dir,
                                     'AnnotationsVisualization',
                                     base + '_viz.jpg')

        # save source image
        imageData = data.get(
            'imageData'
        )  # labelme annotated file contains source image data(serialized)
        if imageData:
            img = utils.img_b64_to_arr(imageData)
        else:
            img_file = osp.join(osp.dirname(label_file), data['imagePath'])
            img = np.asarray(PIL.Image.open(img_file))
        PIL.Image.fromarray(img).save(out_img_file)

        # generate voc format annotation file
        maker = builder.ElementMaker()
        xml = maker.annotation(
            # folder name
            maker.folder(""),
            # img path
            maker.filename(base + '.jpg'),
            # img source, ignore it
            maker.source(
                maker.database(""),
                maker.annotation(""),
                maker.image(""),
            ),
            maker.size(  # image size(height, width and channel)
                maker.height(str(img.shape[0])),
                maker.width(str(img.shape[1])),
                maker.depth(str(img.shape[2])),
            ),
            maker.segmented("0"),  # if for segmentation
        )

        # two list for visualization
        bboxes = []
        labels = []
        for shape in data['shapes']:
            # TODO: change it for annotation shape type, some use points, some use rectangle. Here shows the points one.
            class_name = shape['label']  # object name in json file
            if args.label_dict is not None:
                class_name = fst2snd_dict[class_name]

            class_id = class_names.index(class_name)  # convert to class id
            print("222", shape)

            # box info from annotated points
            xmin = int(shape['points'][0][0])
            ymin = int(shape['points'][0][1])
            xmax = int(shape['points'][1][0])
            ymax = int(shape['points'][1][1])

            # swap if min is larger than max.
            xmin, xmax = sorted([xmin, xmax])
            ymin, ymax = sorted([ymin, ymax])

            bboxes.append([xmin, ymin, xmax, ymax])
            labels.append(class_id)

            xml.append(
                maker.object(  # object info
                    maker.name(class_name),  # label name
                    maker.pose(""),  # pose info, doesn't matter
                    maker.truncated("0"),  # truncated info, doesn't matter
                    maker.difficult("0"),  # diificulty, doesn't matter
                    maker.
                    bndbox(  # bbox(up-left corner and bottom-right corner points)
                        maker.xmin(str(xmin)),
                        maker.ymin(str(ymin)),
                        maker.xmax(str(xmax)),
                        maker.ymax(str(ymax)),
                    ),
                ))

        # caption for visualize drawing
        captions = [class_names[l] for l in labels]
        viz = labelme.utils.draw_instances(img,
                                           bboxes,
                                           labels,
                                           captions=captions)

        PIL.Image.fromarray(viz).save(out_viz_file)

        # another visualize format (colored mask in bbox)
        label_name_to_value = {'_background_': 0}
        for shape in sorted(data['shapes'], key=lambda x: x['label']):
            label_name = shape['label']

            if label_name in label_name_to_value:
                label_value = label_name_to_value[label_name]
            else:
                label_value = len(label_name_to_value)
                label_name_to_value[label_name] = label_value

        lbl = utils.shapes_to_label(img.shape, data['shapes'],
                                    label_name_to_value)
        label_names = [None] * (max(label_name_to_value.values()) + 1)
        for name, value in label_name_to_value.items():
            if args.label_dict is not None:
                name = fst2snd_dict[name]
            label_names[value] = name

        lbl_viz = utils.draw_label(lbl, img, label_names)
        PIL.Image.fromarray(lbl_viz).save(out_colorize_file)

        # save voc annotation to xml file
        with open(out_xml_file, 'wb') as f:
            f.write(etree.tostring(xml, pretty_print=True))
Ejemplo n.º 10
0
    def make_klive(sub):
        try:
            from klive.logic_klive import LogicKlive
            from klive.model import ModelSetting as KliveModelSetting
            if LogicKlive.source_list is None:
                tmp = LogicKlive.channel_load_from_site()
            instance = LogicKlive.source_list['wavve']
            from system.model import ModelSetting as SystemModelSetting

            tmp = builder.ElementMaker(
                nsmap={'itunes': 'http://www.itunes.com/dtds/podcast-1.0.dtd'})
            root = tmp.rss(version="2.0")
            EE = builder.ElementMaker(
                namespace="http://www.itunes.com/dtds/podcast-1.0.dtd",
                nsmap={'itunes': 'http://www.itunes.com/dtds/podcast-1.0.dtd'})
            channel_tag = (E.channel(
                E.title('KLive Radio'),
                E.link(),
                E.description('KLive Radio'),
                E.language('ko-kr'),
                E.copyright(''),
                EE.subtitle(),
                EE.author(),
                EE.summary('KLive Radio'),
                EE.category('Radio'),
                EE.image(),
                EE.explicit('no'),
                EE.keywords('Radio'),
            ))
            root.append(channel_tag)
            for idx, c in enumerate(instance.get_channel_list()):
                if not c.is_tv:
                    logger.debug(c.title)
                    logger.debug(c.current)
                    logger.debug(c.source_id)
                    logger.debug(c.source)
                    url = '%s/klive/api/url.m3u8?m=url&s=%s&i=%s' % (
                        SystemModelSetting.get('ddns'), c.source, c.source_id)
                    if SystemModelSetting.get_bool('auth_use_apikey'):
                        url += '&apikey=%s' % SystemModelSetting.get(
                            'auth_apikey')

                    channel_tag.append(
                        E.item(
                            E.title(c.title),
                            EE.subtitle(c.current),
                            EE.summary(c.current),
                            E.guid(str(idx + 1)),
                            E.pubDate(datetime.now().strftime(
                                '%a, %d %b %Y %H:%M:%S') + ' +0900'),
                            #EE.duration(),
                            E.enclosure(
                                url=url
                            ),  #, length=item['file_size'], type='audio/mp3'),
                            E.description(c.current)))
            return app.response_class(ET.tostring(root,
                                                  pretty_print=True,
                                                  xml_declaration=True,
                                                  encoding="utf-8"),
                                      mimetype='application/xml')
        except Exception as e:
            logger.error('Exception:%s', e)
            logger.error(traceback.format_exc())
Ejemplo n.º 11
0
def to_xml(coloring):
    e = builder.ElementMaker()
    return e.Color(
        *[Component.to_xml(component) for component in coloring["components"]],
        Color=coloring["color"],
    )
Ejemplo n.º 12
0
def config_bgp_openconfig(nc_manager):
    """
        Trying to configure a whole bgp config with openconfig models
    """
    config_bgp = """
<config>
    <bgp xmlns="http://openconfig.net/yang/bgp">
        <global>
            <config>
                <as>100</as>
                <router-id>100.100.100.100</router-id>
            </config>
            <use-multiple-paths>
            </use-multiple-paths>
        </global>
        <peer-groups>
            <peer-group peer-group-name='eBGP_peer'>
                <config>
                    <peer-group-name>eBGP_peer</peer-group-name>
                </config>
            </peer-group>
        </peer-groups>
        <neighbors>
            <neighbor>
                <config>
                    <description>Configured_by_netconfig_based_on_openconfig_yang</description>
                    <peer-as>1234</peer-as>
                    <local-as>5678</local-as>
                    <neighbor-address>1.2.3.4</neighbor-address>
                    <peer-group>eBGP_peer</peer-group>
                    <send-community>BOTH</send-community>
                </config>
                <ebgp-multihop>
                    <config>
                        <multihop-ttl>10</multihop-ttl>
                    </config>
                </ebgp-multihop>
                <logging-options>
                    <config>
                        <log-neighbor-state-changes>true</log-neighbor-state-changes>
                    </config>
                </logging-options>
                <route-reflector>
                    <config>
                        <route-reflector-cluster-id>1234</route-reflector-cluster-id>
                    </config>
                </route-reflector>
                <timers>
                    <config>
                        <hold-time>30</hold-time>
                        <keepalive-interval>10</keepalive-interval>
                        <minimum-advertisement-interval>0</minimum-advertisement-interval>
                        <connect-retry>35</connect-retry>
                    </config>
                </timers>
                <transport>
                    <config>
                        <passive-mode>true</passive-mode>
                    </config>
                </transport>
                <neighbor-address>1.2.3.4</neighbor-address>
            </neighbor>
        </neighbors>
    </bgp>
</config>
    """

    # Could use lxml builder to prepare the config in a lil' more programatic way
    # Example :
    elem_maker = builder.ElementMaker()
    elem_maker_ns = builder.ElementMaker(
        namespace='http://openconfig.net/yang/bgp')
    bgp_elem = elem_maker_ns.bgp
    config_elem = elem_maker.config(bgp_elem)
    etree.tostring(config_elem)

    success = nc_manager.edit_config(config_bgp, target='running')
    print(success)
    def create_xml(cls, invoice, vals):
        head_xml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
        E = builder.ElementMaker()
        #------------ INFOTRIBUTARIA ------------
        street = ''
        if invoice.company.party.addresses[0].street:
            street = invoice.company.party.addresses[0].street
        password = cls.get_password(invoice)
        INFOTRIBUTARIA = {
            'infoTributaria': [
                [
                    ('ambiente', vals['enviroment_type']),
                    ('tipoEmision', vals['broadcast_type']),
                    ('razonSocial', invoice.company.party.name),
                    ('nombreComercial', invoice.company.party.commercial_name),
                    ('ruc', invoice.company.party.vat_number),
                    ('claveAcceso', password),
                    ('codDoc', EVOUCHER_TYPE[vals['evoucher_type']]),
                    ('estab', invoice.pos.code),
                    ('ptoEmi', invoice.pos.code),
                    ('secuencial', vals['number']),
                    ('dirMatriz', street),
                ],
            ]
        }

        #------------ INFOFACTURA ------------
        TOTAL_TAXES = {}

        total_taxes = []
        total_withholdings = []
        total_with_taxes = Decimal(0)

        ret_used_codes = []
        default_ret_codes = ['327', '328', '3']

        for invoice_tax in invoice.taxes:

            if not invoice_tax.tax.group or not invoice_tax.tax.group.code:
                cls.raise_user_error('missing_tax_group', invoice_tax.tax.name)
            if not invoice_tax.tax_code or not invoice_tax.tax_code.code:
                cls.raise_user_error('missing_tax_code', invoice_tax.tax.name)

            if invoice_tax.tax.group.code == GTA_CODE_TAX['IVA']:
                total_taxes.append([
                    ('codigo', invoice_tax.tax.group.code),
                    ('codigoPorcentaje', invoice_tax.tax_code.code),
                    ('baseImponible', fmt2(invoice_tax.base)),
                    ('valor', fmt2(invoice_tax.amount)),
                ])

            if invoice_tax.tax.group.code == GTA_CODE_TAX['RETENCION']:
                total_withholdings.append([
                    ('codigo', invoice_tax.tax.group.code),
                    ('codigoPorcentaje', invoice_tax.tax_code.code),
                    ('tarifa', fmt2(invoice_tax.tax.rate * 100)),
                    ('valor', fmt2(invoice_tax.amount)),
                ])
                ret_used_codes.append(invoice_tax.tax.group.code)

            if invoice_tax.tax.group.code == GTA_CODE_TAX['ICE']:
                pass
            total_with_taxes += invoice_tax.amount

        for ret_code in set(default_ret_codes) - set(ret_used_codes):
            total_withholdings.append([
                ('codigo', '4'),
                ('codigoPorcentaje', ret_code),
                ('tarifa', fmt2(0)),
                ('valor', fmt2(0)),
            ])

        #------------ DETALLES ------------
        detalles = []
        for line in invoice.lines:
            line_taxes = []
            for tax in line.taxes:
                if not tax.group.code == GTA_CODE_TAX['IVA']:
                    continue
                tax_amount = cls.get_invoice_line_tax(line, tax, invoice)
                line_taxes.append([
                    ('codigo', tax.group.code),
                    ('codigoPorcentaje', tax.invoice_tax_code.code),
                    ('tarifa', fmt2(tax.rate * 100)),
                    ('baseImponible', fmt2(line.amount)),
                    ('valor', fmt2(tax_amount)),
                ])
            total_with_taxes += line.amount
            descuento = fmt2(0)
            detalles.append([
                ('codigoPrincipal', line.product.code),
                ('descripcion', line.product.name),
                ('cantidad', fmt6(line.quantity)),
                ('precioUnitario', fmt6(line.unit_price)),
                ('descuento', descuento),
                ('precioTotalSinImpuesto', fmt2(line.amount)),
                ('impuestos', {
                    'impuesto': line_taxes
                }),
            ])
        DETALLE = {'detalle': detalles}

        #------------ RETENCIONES ------------
        RETENCIONES = {'retencion': total_withholdings}

        #------------ INFOADICIONAL ------------
        INFOAD = []
        if invoice.party.addresses[0].street:
            INFOAD.append(
                E.campoAdicional(
                    invoice.party.addresses[0].street,
                    nombre='Direccion',
                ))
        if invoice.party.email:
            INFOAD.append(
                E.campoAdicional(
                    invoice.party.email,
                    nombre='Email',
                ))

        TOTAL_TAXES['totalImpuesto'] = total_taxes
        tip = Decimal(0)
        importeTotal = total_with_taxes + tip
        totalDescuento = fmt2(0)
        INFOFACTURA = {
            'infoFactura': [
                [
                    ('fechaEmision',
                     vals['release_date'].strftime('%d/%m/%Y')),
                    ('dirEstablecimiento', street),
                    ('contribuyenteEspecial', '12345'),
                    ('obligadoContabilidad',
                     invoice.party.mandatory_accounting.upper()),
                    ('tipoIdentificacionComprador',
                     invoice.party.type_document),
                    ('razonSocialComprador', invoice.party.name),
                    ('identificacionComprador', invoice.party.vat_number),
                    ('totalSinImpuestos', fmt2(invoice.untaxed_amount)),
                    ('totalDescuento', totalDescuento),
                    ('totalConImpuestos', TOTAL_TAXES),
                    ('propina', fmt2(tip)),
                    ('importeTotal', fmt2(importeTotal)),
                    ('moneda', 'DOLAR'),
                ],
            ]
        }

        infoTributaria_ = cls.metaprocess_xml(INFOTRIBUTARIA)[0]
        infoFactura_ = cls.metaprocess_xml(INFOFACTURA)[0]
        infoAdicional_ = E.infoAdicional(*INFOAD)
        detalles_ = E.detalles(*cls.metaprocess_xml(DETALLE))
        retenciones_ = E.retenciones(*cls.metaprocess_xml(RETENCIONES))

        evoucher = E.factura(
            infoTributaria_,
            infoFactura_,
            detalles_,
            retenciones_,
            infoAdicional_,
            id="comprobante",
            version="1.1.2",
        )
        body = etree.tostring(evoucher, pretty_print=True)
        return (head_xml + body)
Ejemplo n.º 14
0
def to_xml(plane):
    e = builder.ElementMaker()
    return e.ClippingPlane(
        e.Location(*XYZ.to_xml(plane["location"])),
        e.Direction(*XYZ.to_xml(plane["direction"])),
    )
Ejemplo n.º 15
0
import cmath
import enum
import math
import os
from typing import Tuple

from cairosvg import svg2png
from lxml import builder, etree

from letsgo.track import Position

SVG = builder.ElementMaker(
    namespace="http://www.w3.org/2000/svg", nsmap={None: "http://www.w3.org/2000/svg"}
)


def hex_to_rgb(value) -> Tuple[float, float, float]:
    return (
        int(value[1:3], 16) / 255,
        int(value[3:5], 16) / 255,
        int(value[5:7], 16) / 255,
    )


class Colors(enum.Enum):
    dark_bluish_gray = "#5B6770"
    tan = "#aaaaaa"
    red = "#ffaaaa"

    @property
    def rgb(self) -> Tuple[float, float, float]:
Ejemplo n.º 16
0
from collections import OrderedDict
from lxml import builder, etree
from termcolor import colored

from wscheck.checker import RULES

BUILD = builder.ElementMaker()


class ErrorPrinter(object):
    def __init__(self, files, issues):
        """
        :type files: list
        :type issues: list
        """
        self._files = sorted(files)
        self._issues = sorted(issues,
                              key=lambda issue:
                              (issue['path'], issue['line'], issue['col']))

    def print_to_tty(self, colored_output):
        """
        :type colored_output: bool
        """
        glue_text = ''

        for issue in self._issues:
            context = issue['context']
            message_indent = issue['col'] - 1
            message = self._get_message(issue)
Ejemplo n.º 17
0
class AtomFeed(object):

    TIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ%z'

    ATOM_NS = 'http://www.w3.org/2005/Atom'
    APP_NS = 'http://www.w3.org/2007/app'
    #xhtml_ns = 'http://www.w3.org/1999/xhtml'
    DCTERMS_NS = 'http://purl.org/dc/terms/'
    OPDS_NS = 'http://opds-spec.org/2010/catalog'
    SCHEMA_NS = 'http://schema.org/'

    SIMPLIFIED_NS = "http://librarysimplified.org/terms/"
    BIBFRAME_NS = "http://bibframe.org/vocab/"

    nsmap = {
        None: ATOM_NS,
        'app': APP_NS,
        'dcterms': DCTERMS_NS,
        'opds': OPDS_NS,
        'schema': SCHEMA_NS,
        'simplified': SIMPLIFIED_NS,
        'bibframe': BIBFRAME_NS,
    }

    default_typemap = {datetime: lambda e, v: _strftime(v)}
    E = builder.ElementMaker(typemap=default_typemap, nsmap=nsmap)
    SIMPLIFIED = builder.ElementMaker(typemap=default_typemap,
                                      nsmap=nsmap,
                                      namespace=SIMPLIFIED_NS)
    SCHEMA = builder.ElementMaker(typemap=default_typemap,
                                  nsmap=nsmap,
                                  namespace=SCHEMA_NS)

    @classmethod
    def _strftime(self, date):
        """
        Format a date the way Atom likes it (RFC3339?)
        """
        return date.strftime(self.TIME_FORMAT)

    @classmethod
    def add_link_to_feed(cls, feed, children=None, **kwargs):
        link = cls.E.link(**kwargs)
        feed.append(link)
        if children:
            for i in children:
                link.append(i)

    @classmethod
    def add_link_to_entry(cls, entry, children=None, **kwargs):
        #links.append(E.link(rel=rel, href=url, type=image_type))
        link = cls.E.link(**kwargs)
        entry.append(link)
        if children:
            for i in children:
                link.append(i)

    @classmethod
    def author(cls, *args, **kwargs):
        return cls.E.author(*args, **kwargs)

    @classmethod
    def category(cls, *args, **kwargs):
        return cls.E.category(*args, **kwargs)

    @classmethod
    def entry(cls, *args, **kwargs):
        return cls.E.entry(*args, **kwargs)

    @classmethod
    def id(cls, *args, **kwargs):
        return cls.E.id(*args, **kwargs)

    @classmethod
    def link(cls, *args, **kwargs):
        return cls.E.link(*args, **kwargs)

    @classmethod
    def makeelement(cls, *args, **kwargs):
        return cls.E._makeelement(*args, **kwargs)

    @classmethod
    def name(cls, *args, **kwargs):
        return cls.E.name(*args, **kwargs)

    @classmethod
    def schema_(cls, field_name):
        return "{%s}%s" % (cls.SCHEMA_NS, field_name)

    @classmethod
    def summary(cls, *args, **kwargs):
        return cls.E.summary(*args, **kwargs)

    @classmethod
    def title(cls, *args, **kwargs):
        return cls.E.title(*args, **kwargs)

    @classmethod
    def update(cls, *args, **kwargs):
        return cls.E.update(*args, **kwargs)

    @classmethod
    def updated(cls, *args, **kwargs):
        return cls.E.updated(*args, **kwargs)

    def __init__(self, title, url):
        self.feed = self.E.feed(
            self.E.id(url),
            self.E.title(title),
            self.E.updated(self._strftime(datetime.datetime.utcnow())),
            self.E.link(href=url, rel="self"),
        )

    def __unicode__(self):
        if self.feed is None:
            return None

        string_tree = etree.tostring(self.feed, pretty_print=True)
        return string_tree.encode("utf8")
HERE = Path(__file__).parent
DATA = (HERE / ".." / "data").resolve()
NO_UNIHAN_XML = DATA / "ucd.nounihan.flat.xml"
UNIHAN_XML = DATA / "ucd.unihan.flat.xml"

if not NO_UNIHAN_XML.is_file():
    quit(
        "Run `wget https://www.unicode.org/Public/UCD/latest/ucdxml/ucd.nounihan.flat.zip && unzip ucd.nounihan.flat.zip` to get the XML file. (File sizes: .zip=912K; .xml: 51M.)"
    )
elif not UNIHAN_XML.is_file():
    quit(
        "Run `wget https://www.unicode.org/Public/UCD/latest/ucdxml/ucd.unihan.flat.zip && unzip ucd.unihan.flat.zip` to get the XML file. (File sizes: .zip=6.1M; .xml: 40M.)"
    )

# Define tags for the XML.
elt = builder.ElementMaker(namespace="http://www.unicode.org/ns/2003/ucd/1.0")
char_tag = elt.char().tag

# # Define Unihan ranges.
# UNIHAN_LO = 0x4E00
# UNIHAN_HI = 0x9FFF
# UNIHAN_EXT_A_LO = 0x3400
# UNIHAN_EXT_A_HI = 0x4DBF
# UNIHAN_EXT_B_LO = 0x20000
# UNIHAN_EXT_B_HI = 0x2A6DF
# UNIHAN_EXT_C_LO = 0x2A700
# UNIHAN_EXT_C_HI = 0x2B73F
# UNIHAN_EXT_D_LO = 0x2B740
# UNIHAN_EXT_D_HI = 0x2B81F

# Get data for Tangut.
Ejemplo n.º 19
0
def to_xml(component):
    e = builder.ElementMaker()
    children = []
    if (originating_system := component.get("originating_system")) is not None:
        children.append(e.OriginatingSystem(originating_system))
Ejemplo n.º 20
0
#
import base64
from endesive import xades
import time
import datetime
import hashlib
import io
import uuid

from cryptography.x509.oid import NameOID
from lxml import etree, builder
import requests
from asn1crypto import cms, algos, core, keys, pem, tsp, x509, util

DS = builder.ElementMaker(
    namespace="http://www.w3.org/2000/09/xmldsig#",
    nsmap={"ds": "http://www.w3.org/2000/09/xmldsig#"},
)
CanonicalizationMethod = DS.CanonicalizationMethod
DigestMethod = DS.DigestMethod
DigestValue = DS.DigestValue
KeyInfo = DS.KeyInfo
Object = DS.Object
Reference = DS.Reference
Signature = DS.Signature
SignatureMethod = DS.SignatureMethod
SignatureValue = DS.SignatureValue
SignedInfo = DS.SignedInfo
Transform = DS.Transform
Transforms = DS.Transforms
X509Certificate = DS.X509Certificate
X509Data = DS.X509Data
Ejemplo n.º 21
0
 def wrapped(context, previous_result):
     setattr(context, name, builder.ElementMaker(**kwargs))
     return previous_result
Ejemplo n.º 22
0
    'soap': 'http://schemas.xmlsoap.org/soap/envelope/',
    't': 'http://schemas.microsoft.com/exchange/services/2006/types',
    'sp': 'http://schemas.microsoft.com/sharepoint/soap/',
    'spd': 'http://schemas.microsoft.com/sharepoint/soap/directory/',
    'rs': 'urn:schemas-microsoft-com:rowset',
    'ups': 'http://microsoft.com/webservices/SharePointPortalServer/UserProfileService/GetUserProfileByIndex',
    'd': 'http://schemas.microsoft.com/ado/2007/08/dataservices',
    'm': 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata',
    'search': 'urn:Microsoft.Search',
    'sq': 'urn:Microsoft.Search.Query',
    'sr': 'urn:Microsoft.Search.Response',
    'srd': 'urn:Microsoft.Search.Response.Document',
    'z': '#RowsetSchema', # Yes, really.
    'sharepoint': 'https://github.com/ox-it/python-sharepoint/', # Ours
}

SOAP = builder.ElementMaker(namespace=namespaces['soap'], nsmap=namespaces)
T = builder.ElementMaker(namespace=namespaces['t'], nsmap=namespaces)
SP = builder.ElementMaker(namespace=namespaces['sp'], nsmap=namespaces)
SPD = builder.ElementMaker(namespace=namespaces['spd'], nsmap=namespaces)
UPS = builder.ElementMaker(namespace=namespaces['ups'], nsmap=namespaces)
SQ = builder.ElementMaker(namespace=namespaces['sq'], nsmap=namespaces)

OUT = builder.ElementMaker(namespace=namespaces['sharepoint'], nsmap=namespaces)

SEARCH = builder.ElementMaker(namespace=namespaces['search'], nsmap={None: namespaces['search']})
SQ = builder.ElementMaker(namespace=namespaces['sq'], nsmap={None: namespaces['sq']})

def soap_body(*args, **kwargs):
    return SOAP.Envelope(SOAP.Body(*args, **kwargs))
Ejemplo n.º 23
0
def writeSVG(outfn, parts, viewport_size, margin=0, outermargin=0, units="mm"):
  minx = 12000
  miny = 12000
  vp_max_width = 0
  vp_max_height = 0
  dimx = 0
  dimy = 0

  for n,part in enumerate(parts):
    minx = min(minx, part.x)
    miny = min(miny, part.y)

    dimx += part.bbox[0]
    dimy = max(dimy, part.bbox[1])

    vp_max_width = max(vp_max_width, part.viewbox[2])
    vp_max_height = max(vp_max_height, part.viewbox[3])

  #logging.debug("minx:%s miny:%s" % (minx, miny))

  miny = 9400

  fp = open(outfn, "w")
  fp.write('<?xml version="1.0" encoding="UTF-8"?>\n')
  fp.write('<svg xmlns="http://www.w3.org/2000/svg"\n')
  fp.write('  xmlns:xlink="http://www.w3.org/1999/xlink"\n')
  fp.write('  xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"\n')
  fp.write('  xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"\n')
  fp.write('  sodipodi:docname="box.svg"\n')

  fp.write('  width="%d%s" height="%d%s"\n' % (viewport_size[0], units, viewport_size[1], units))
  viewBox = (minx-outermargin*2, miny+outermargin, viewport_size[0], viewport_size[1])
  fp.write('  viewBox="%d %d %d %d"\n' % viewBox)
  fp.write('  version="1.1">\n')

  fp.write('<sodipodi:namedview id="namedview312" inkscape:document-units="%s" />\n' % units)
  fp.write("</svg>\n")
  fp.close()
  
  parser = et.XMLParser(remove_blank_text=True)
  body = open(outfn, "r")
  dest_tree = et.parse(outfn, parser)
  dest_root = dest_tree.getroot()

  xlink = '{http://www.w3.org/1999/xlink}href'
  crosses = []
  bounding_boxes = []

  for n, part in enumerate(parts):
    x1 = viewBox[0]+part.x 
    y1 = viewBox[1]+viewBox[3]-part.y
    x2 = x1 + part.bsize[0]
    y2 = y1 - part.bsize[1]

    if 0:
      bounding_boxes.append(rect(x1,y1,x2,y2))
      bounding_boxes.append(polyline(x1,y1,part.hull))
    
    for el in part.tree.getroot():
      dest_root.append(el)

      cx = viewBox[0]+part.x + part.bbox[0]//2
      cy = viewBox[1]+viewBox[3]-part.y - part.bbox[1]//2
      #crosses.append(cross((cx, cy), 10))

      cx = viewBox[0]+part.x + margin
      cy = viewBox[1]+viewBox[3]-part.y - margin 
      crosses.append(cross((cx, cy), 10))


      if el.tag.endswith("g"):
        if part.rotated:
          rotation = 90
          el.set("transform", 'rotate(%d %d %d) translate(%d %d)' % (rotation, 
                                                                     cx, cy,
                                                                     part.x - part.bbox[0], 
                                                                     -part.y))
        else:
          el.set("transform", 'translate(%d %d)' % (part.x - outermargin*2 - margin*2,
                                                    -(part.y - outermargin*2 - margin*2)))
      elif el.tag.endswith("defs"):
        for child in el.iterfind(".//{%s}symbol" % svg_ns):
          child.attrib['id'] = child.attrib['id'].replace("glyph", "glyph%d_" % n)
      for child in el.iterfind(".//{%s}use" % svg_ns):
        if xlink in child.attrib:
          child.attrib[xlink] = child.attrib[xlink].replace("glyph", "glyph%d_" % n)

  if 0:
    E = builder.ElementMaker(namespace=svg_ns)
    group = E.g(transform="translate(%d %d)" % (outermargin, outermargin))
    dest_root.insert(0, group)

  if 1:
    for _box in bounding_boxes:
      dest_root.append(_box)

  if 0:
    for _cross in crosses:
      dest_root.append(_cross)

  if 0:
    dest_root.append(cross((0,0)))
    dest_root.append(cross((viewBox[0], viewBox[1])))
    dest_root.append(cross((viewBox[0]+viewBox[2], viewBox[1])))
    dest_root.append(cross((viewBox[0]+viewBox[2], viewBox[1]+viewBox[3])))
    dest_root.append(cross((viewBox[0], viewBox[1]+viewBox[3])))

  et.ElementTree(dest_root).write(outfn, pretty_print=True, encoding='utf-8', xml_declaration=True)
Ejemplo n.º 24
0
def _strftime(d):
    """
    Format a date the way Atom likes it (RFC3339?)
    """
    return d.strftime('%Y-%m-%dT%H:%M:%SZ%z')

## try:
##     from lxml import builder
## except ImportError:
##     pass
## else:
##     E = builder.ElementMaker(parser=atom_parser,
##                              typemap={datetime: lambda e, v: _strftime(v)})
from lxml import builder
E = builder.ElementMaker(#parser=atom_parser,
                         typemap={datetime: lambda e, v: _strftime(v)})
__all__.append('E')

class NoDefault:
    pass

class _LiveList(list):
    """
    This list calls on_add or on_remove whenever the list is modified.
    """
    on_add = on_remove = None
    name = None
    def __init__(self, *args, **kw):
        on_add = on_remove = name = None
        if 'on_add' in kw:
            on_add = kw.pop('on_add')
Ejemplo n.º 25
0
def cross(pos, size=50):
  E = builder.ElementMaker(namespace=svg_ns)
  group = E.g()
  group.append(E.line(x1=str(pos[0]-size), y1=str(pos[1]), x2=str(pos[0]+size), y2=str(pos[1]), style="stroke:rgb(255,0,0);stroke-width:2"))
  group.append(E.line(x1=str(pos[0]), y1=str(pos[1]-size), x2=str(pos[0]), y2=str(pos[1]+size), style="stroke:rgb(255,0,0);stroke-width:2"))
  return group
Ejemplo n.º 26
0
def to_xml(line):
    e = builder.ElementMaker()
    return e.Line(
        e.StartPoint(*XYZ.to_xml(line["start_point"])),
        e.EndPoint(*XYZ.to_xml(line["end_point"])),
    )
Ejemplo n.º 27
0
import logging
import time
import os
import glob
import shutil
import lxml.etree as etree
import lxml.builder as builder

import antd.plugin as plugin
import antd.garmin as garmin

_log = logging.getLogger("antd.tcx")

E = builder.ElementMaker(
    nsmap={
        None: "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2",
        "ext": "http://www.garmin.com/xmlschemas/ActivityExtension/v2",
        "xsi": "http://www.w3.org/2001/XMLSchema-instance",
    })

X = builder.ElementMaker(
    namespace="http://www.garmin.com/xmlschemas/ActivityExtension/v2")


class TcxPlugin(plugin.Plugin):

    tcx_output_dir = "."

    def data_availible(self, device_sn, format, files):
        if "raw" != format: return files
        processed = []
        result = []
Ejemplo n.º 28
0
    def make_xml(self):
        self.ensure_one()
        domain = safe_eval(self.domain)
        context = safe_eval(self.context)

        product_ids = self.env['product.template'].sudo().with_context(
            context).search(domain, limit=self.limit)

        E = builder.ElementMaker()
        rss = etree.Element("rss", nsmap=MY_NAMESPACES, version="2.0")

        channel = E.channel(E.title(self.name), E.link(self.website_id.domain),
                            E.description(self.name))
        rss.append(channel)

        for product_id in product_ids:
            item = E.item()
            sku = etree.Element('{%s}id' % MY_NAMESPACES['g'])
            sku.text = product_id['default_code'] if product_id[
                'default_code'] else 'p-%i' % product_id['default_code']
            item.append(sku)

            if product_id['barcode']:
                gtin = etree.Element('{%s}gtin' % MY_NAMESPACES['g'])
                gtin.text = product_id['barcode']
                item.append(gtin)

            if product_id['default_code']:
                mpn = etree.Element('{%s}mpn' % MY_NAMESPACES['g'])
                mpn.text = product_id['default_code']
                item.append(mpn)

            title = etree.Element('title')
            title.text = product_id['name']
            item.append(title)

            description = etree.Element('description')
            if product_id['description']:
                description.text = re.sub(CLEANTAG, '',
                                          product_id['description'])
            else:
                description.text = product_id['name']
            item.append(description)

            availability = etree.Element('{%s}availability' %
                                         MY_NAMESPACES['g'])
            if product_id.qty_available > 0:
                availability.text = 'in stock'
            else:
                availability.text = 'preorder'
            item.append(availability)

            brand = etree.Element('{%s}brand' % MY_NAMESPACES['g'])
            if 'product_brand_id' in product_id and len(
                    product_id.product_brand_id):
                brand.text = product_id.product_brand_id.name
            else:
                brand.text = self.website_id.name
            item.append(brand)

            link = etree.Element('link')
            link.text = "%s/%s%s" % (self.website_id.domain, self.base_url,
                                     slugify(product_id))
            item.append(link)

            price = etree.Element('{%s}price' % MY_NAMESPACES['g'])

            # to-do: calcular impuestos y currency
            if 'pack' in product_id and product_id.pack:
                price.text = "%.2f %s" % (product_id._price_get([
                    product_id
                ])[product_id.id], self.env.company.currency_id.name)

            else:
                #to-do tax ? product_id['list_price']
                price.text = "%.2f %s" % (product_id['list_price'],
                                          self.env.company.currency_id.name)

            item.append(price)

            if product_id['image_1024']:
                image_link = etree.Element('{%s}image_link' %
                                           MY_NAMESPACES['g'])
                image_link.text = '%s/web/image/product.product/%i/image_1024/' % (
                    self.website_id.domain, product_id.id)
                item.append(image_link)
            else:
                pass
                #add default IMG

            #additional_image_link
            condition = etree.Element('{%s}condition' % MY_NAMESPACES['g'])
            condition.text = 'new'
            item.append(condition)

            if not product_id['default_code'] or not product_id['barcode']:
                identifier_exists = etree.Element('{%s}identifier_exists' %
                                                  MY_NAMESPACES['g'])
                identifier_exists.text = 'no'
                item.append(identifier_exists)

            google_product_category = etree.Element(
                '{%s}google_product_category' % MY_NAMESPACES['g'])

            if len(product_id.producttype_id):
                google_product_category.text = str(
                    product_id.producttype_id.tax_id)
            elif (len(product_id.categ_id.producttype_id)):
                google_product_category.text = str(
                    product_id.categ_id.producttype_id.tax_id)
            else:
                google_product_category.text = str(self.producttype_id.tax_id)
            item.append(google_product_category)

            channel.append(item)

        return etree.tostring(rss,
                              xml_declaration=True,
                              encoding="utf-8",
                              pretty_print=True)
Ejemplo n.º 29
0
def create(headerdicts, values, filename="pixml_for_lizard.xml", timeZone=0.0):
    """
    Args:
        values(iterable): [(date_time, value, flag), ...]
        headerdicts(iterable): [{*}, ...]
            * one of the Headerelements below with a value
    """
    schema = "http://www.wldelft.nl/fews/PI"
    xsi = "http://www.w3.org/2001/XMLSchema-instance"
    Element = builder.ElementMaker(nsmap={None: schema, 'xsi': xsi})
    TimeZone = Element.timeZone
    Root = Element.TimeSeries
    Event = Element.event
    Series = Element.series
    Header = Element.header
    Headerelements = {
        'type': Element.type,
        'moduleInstanceId': Element.moduleInstanceId,
        'locationId': Element.locationId,
        'parameterId': Element.parameterId,
        'timeStep': Element.timeStep,
        'startDate': Element.startDate,
        'endDate': Element.endDate,
        'missVal': Element.missVal,
        'stationName': Element.stationName,
        'lat': Element.lat,
        'lon': Element.lon,
        'x': Element.x,
        'y': Element.y,
        'units': Element.units
    }

    order = [
        "type", "moduleInstanceId", "locationId", "parameterId", "timeStep",
        "startDate", "endDate", "missVal", "stationName", "lat", "lon", "units"
    ]
    header_order = [x for x in order if x in next(iter(headerdicts.values()))]
    for key in list(values.keys()):
        valueelements = values[key]
        headerelements = headerdicts[key]
        print('processing', key)
        event_elements = []
        min_date = datetime.datetime.now()
        max_date = datetime.datetime(1, 1, 1)
        for value in valueelements:
            min_date = min(min_date, value["datetime"])
            max_date = max(max_date, value["datetime"])
            date, time = value["datetime"].strftime('%Y-%m-%d %H:%M:%S').split(
                ' ')
            event_elements.append(
                Event(date=date,
                      time=time,
                      value=str(value["value"]),
                      flag=str(value["flag"])))
        header_elements = []
        for name in header_order:
            value = None
            if name == "startDate":
                date, time = min_date.strftime('%Y-%m-%d %H:%M:%S').split(' ')
                val_dict = {"date": date, "time": time}
            elif name == "endDate":
                date, time = max_date.strftime('%Y-%m-%d %H:%M:%S').split(' ')
                val_dict = {"date": date, "time": time}
            elif name == "timeStep":
                val_dict = headerelements[name]
            else:
                value = str(headerelements[name])
            if value:
                header_elements.append(Headerelements[name](value))
            else:
                header_elements.append(Headerelements[name](**val_dict))
        header = Header(*header_elements)
        series = Series(header, *event_elements)
        print('removing {}'.format(key))
        del values[key]
        del headerdicts[key]
        write_xml_to_file(filename + '.tmp', series)
    timeZone = TimeZone(str(timeZone))
    root = Root(timeZone)
    root.attrib['{{{pre}}}schemaLocation'.format(pre=xsi)] = \
        "http://www.wldelft.nl/fews/PI http://fews.wldelft.nl/schemas/" \
        "version1.0/pi-schemas/pi_timeseries.xsd"
    root.attrib['version'] = "1.17"
    root_string = etree.tostring(root,
                                 pretty_print=True,
                                 xml_declaration=True,
                                 encoding='utf-8').decode('utf-8')
    begin = '\n'.join(root_string.split('\n')[:3])
    end = '\n'.join(root_string.split('\n')[3:])
    with open(filename, 'w') as f:
        f.write(begin)
        with open(filename + '.tmp', 'r') as f2:
            for line in f2:
                f.write(line)
        f.write(end)
    os.remove(filename + '.tmp')