Add to_directory method to relevant object classes
[oam.git] / code / network-generator / network_generation / view / network_viewer.py
1 # Copyright 2023 highstreet technologies GmbH
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # !/usr/bin/python
16 """
17 Provides functions to convert the Network into different formats
18 """
19
20 import gzip
21 import json
22 from typing_extensions import Buffer
23 import zipfile
24 import xml.etree.ElementTree as ET
25 from typing import Any
26
27 from network_generation.model.python.o_ran_network import ORanNetwork
28
29
30 class NetworkViewer:
31     """
32     This class contains all functions converting the Network into
33     different formats
34     """
35
36     # constructor
37     def __init__(self, network: ORanNetwork) -> None:
38         self.__network = network
39
40     # json format
41
42     def json(self) -> "NetworkViewer":
43         """
44         Getter returns the class as json object
45         :return The class itself, as it is json serializable
46         """
47         return self
48
49     def show_as_json(self) -> None:
50         """
51         Method printing the class in json format.
52         """
53         print(self.__network.json())
54
55     def show(self) -> None:
56         """
57         Method printing the network
58         """
59         print(self.__network)
60
61     def to_directory(self, parent_dir: str) -> None:
62         """
63         Method converting the network to a subdirectory file structure
64         """
65         self.__network.to_directory(parent_dir)
66         print(f'Directory structure saved to "{parent_dir}"')
67
68     def save(self, filename: str, compressed: bool = True) -> None:
69         """
70         Method saving the class content to a file in json format.
71         :param filename: A valid path to a file on the system.
72         :param compressed: if True, svg is stored as svgz format.
73         :type filename: string
74         """
75         output: dict[str, Any] = self.__network.to_topology()
76         if compressed is True:
77             with gzip.open(f'{filename}-operational.json.gz', 'wb') as zf:
78                 zf.write(json.dumps(output, indent=2).encode('utf-8'))
79             print(f'File "{filename}-operational.json.gz" saved!')
80         else:
81             with open(
82                 f'{filename}-operational.json', "w", encoding="utf-8"
83             ) as jf:
84                 json.dump(output, jf, ensure_ascii=False, indent=2)
85             print(f'File "{filename}-operational.json" saved!')
86
87     def readStylesFromFile(self) -> str:
88         """
89         Method reading the css styles from known file
90         return: content of the file as string
91         """
92         with open("network_generation/view/svg.style.css") as styles:
93             content = styles.read()
94             return content
95
96     def svg(self, filename: str, compressed: bool = True) -> None:
97         """
98         Method saving the class content to a file in xml/svg format.
99
100         :param filename: A valid path to a file on the system.
101         :param compressed: if True, svg is stored as svgz format.
102         :type filename: string
103         """
104         root = self.__network.toSvg()
105         style = ET.Element("style")
106         style.text = self.readStylesFromFile()
107         root.findall(".//desc")[0].append(style)
108
109         if compressed is True:
110             svg_output: Buffer = ET.tostring(
111                 root, encoding="utf-8", xml_declaration=True)
112             with gzip.open(f'{filename}.svgz', 'wb') as zf:
113                 zf.write(svg_output)
114             print(f'File "{filename}.svgz" saved!')
115         else:
116             ET.ElementTree(root).write(
117                 f'{filename}.svg', encoding="utf-8", xml_declaration=True
118             )
119             print(f'File "{filename}.svg" saved!')
120
121     def kml(self, filename: str, compressed: bool = True) -> None:
122         """
123         Method saving the class content to a file in xml/kml format.
124
125         :param filename: A valid path to a file on the system.
126         :param compressed: if True, kml is stored as kmz format.
127         :type filename: string
128         """
129         root = self.__network.toKml()
130         with open("network_generation/view/kml.styles.json") as kml_styles:
131             styles: dict[str, dict] = json.load(kml_styles)
132             for key, value in styles.items():
133                 # add style
134                 style = ET.Element("Style", {"id": key})
135                 line_style = ET.SubElement(style, "LineStyle")
136                 color = ET.SubElement(line_style, "color")
137                 color.text = str(value["stroke"]["color"])
138                 width = ET.SubElement(line_style, "width")
139                 width.text = str(value["stroke"]["width"])
140                 poly_style = ET.SubElement(style, "PolyStyle")
141                 fill = ET.SubElement(poly_style, "color")
142                 fill.text = str(value["fill"]["color"])
143                 root.findall(".//Document")[0].append(style)
144
145         kml: str = ET.tostring(
146             root, encoding="utf-8", xml_declaration=True)
147         if compressed is True:
148             with zipfile.ZipFile(
149                 f'{filename}.kmz', 'w', zipfile.ZIP_DEFLATED
150             ) as zf:
151                 zf.writestr(f'{filename.split("/")[1]}.kml', data=kml)
152             print(f'File "{filename}.kmz" saved!')
153         else:
154             kml_file = open(f'{filename}.kml', 'w')
155             kml_file.write(kml)
156             kml_file.close()
157             print(f'File "{filename}.kml" saved!')