File size: 6,839 Bytes
e235936
 
 
 
 
a6e2a64
4bf380c
 
 
 
 
 
e235936
a6e2a64
e235936
9494f28
 
e235936
4bf380c
 
 
e235936
9494f28
 
c49ded2
 
a6e2a64
c49ded2
e235936
052a6c6
 
e235936
 
052a6c6
 
e235936
052a6c6
 
 
 
 
 
e235936
052a6c6
 
9268c51
052a6c6
e235936
 
052a6c6
 
0fbfb39
 
052a6c6
 
 
 
 
 
 
 
 
 
 
9268c51
 
 
 
 
 
052a6c6
 
 
410319c
 
 
 
9268c51
052a6c6
 
 
 
 
9268c51
 
 
 
052a6c6
 
 
 
 
 
 
 
 
9268c51
 
 
410319c
 
 
 
 
 
 
 
9268c51
 
052a6c6
 
 
9268c51
052a6c6
 
 
 
 
 
 
 
 
 
 
 
9268c51
 
 
 
052a6c6
 
9268c51
 
 
 
052a6c6
9268c51
052a6c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
410319c
052a6c6
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# Hugging Face Hack

import subprocess
import os

dotnet_check_command = "dotnet --list-sdks"
dotnet_install_commands = [
    "wget https://dot.net/v1/dotnet-install.sh -O dotnet-install.sh",
    "chmod +x ./dotnet-install.sh",
    "./dotnet-install.sh --version latest"
]

try:
    print(subprocess.check_output(dotnet_check_command, shell=True))
except:
    print(os.environ["PATH"])

    print("Try to install .net dependency")

    for command in dotnet_install_commands:
        os.system(command)

    os.environ["PATH"] += os.pathsep + "/home/user/.dotnet"
    
    print(os.environ["PATH"])

    os.system(dotnet_check_command)
    # print(subprocess.check_output("dotnet -list-sdk"))

import gradio as gr

# Setup Python.Net

from pythonnet import load

load("coreclr", runtime_config="lib/JTSParser.runtimeconfig.json")

import clr
from System import Reflection

import os

lib_path = os.path.abspath("lib/JTSParser.dll")

Reflection.Assembly.LoadFile(lib_path)
from YYZ import JTS

# App

import numpy as np
import plotly.graph_objects as go
import plotly
print(f"plotly_version={plotly.__version__}")
import math

def dock(x, limit):
    x1 = math.floor(x)
    yield x1
    x2 = min(math.ceil(x), limit)
    if x2 != x1:
        yield x2

default_path = "JTS_assets/ridge.map"

road_names_map = {
    "NB": ["Path", "Road", "Pike", "Rail"],
    "CWB": ["Trail", "Road", "Pike", "Rail"],
    "PZC": ["Trail", "Secondary", "Primary", "Rail"]
}

with gr.Blocks(analytics_enabled=False) as demo:
    with gr.Row():
        with gr.Column(scale=1):
            plot_button = gr.Button("Plot")
            with gr.Row():
                file_input = gr.File(default_path, label="Map File (NB/CWB/PZC)", file_types=[".map"])
                sub_file_input = gr.File(label="Sub Map File (optional)", file_types=[".map"])
            code_dropdown = gr.Dropdown(choices=["NB", "CWB", "PZC"], value="NB", label="Series")
            labels_checkbox = gr.Checkbox(True, label="Labels")
            labels_size_threshold_number = gr.Number(0, label="Label Size Threshold", info="1 => Tactical, 2 => Normal, 3 => Important")
            # with gr.Row():
            with gr.Accordion("Roads"):
                with gr.Row():
                    path_checkbox = gr.Checkbox(label="Path/Trail")
                    road_checkbox = gr.Checkbox(label="Road/Secondary")
                    pike_checkbox = gr.Checkbox(True, label="Pike/Primary")
                    railway_checkbox = gr.Checkbox(True, label="Rail")
            with gr.Row():
                road_offset_number = gr.Number(0.3, label="Road Offset")
                elevation_scale_number = gr.Number(0.1, label="Elevation Scale")
        with gr.Column(scale=2):
            output_plot = gr.Plot()
    
    def plot(data):
        with open(data[file_input].name) as f:
            map_str = f.read()

        code = data[code_dropdown]
        map_file = JTS.JTSParser.FromCode(code).ParseMap(map_str, False)

        if data[sub_file_input]:
            with open(data[sub_file_input].name) as f:
                sub_map_str = f.read()
            sub_map_file = JTS.SubMapFile()
            sub_map_file.Extract(sub_map_str)
            sub_map_file.ApplyTo(map_file)

        network = JTS.HexNetwork.FromMapFile(map_file)
        
        height_mat = np.empty([map_file.Height, map_file.Width])
        for i in range(map_file.Height):
            for j in range(map_file.Width):
                height_mat[i,j] = network.HexMat[i, j].Height

        surface = go.Surface(
            x = np.arange(map_file.Width),
            y = np.arange(map_file.Height),
            z = height_mat
        )

        gl = []

        road_offset = data[road_offset_number]

        road_items = [
            (path_checkbox, 'gray'),
            (road_checkbox, 'green'),
            (pike_checkbox, 'pink'),
            (railway_checkbox, 'black')
        ]

        for road_idx, (checkbox, color) in enumerate(road_items):
            road_name = road_names_map[code][road_idx]
            road_type = map_file.CurrentTerrainSystem.Road.GetValue(road_name)

            if data[checkbox]:
                for road in network.SimplifyRoad(road_type):
                    x_line = []
                    y_line = []
                    z_line = []

                    for node in road:
                        x_line.append(node.X)
                        y_line.append(node.Y)
                        z_line.append(node.Height + road_offset)
                        
                    g = go.Scatter3d(
                        x=x_line, y=y_line, z=z_line,
                        line=dict(
                            color=color,
                            width=2
                        )
                    )
                    
                    gl.append(g)

        fig = go.Figure([surface] + gl)


        scene = {
            "aspectratio": {"x": 1, "y": 1, "z": data[elevation_scale_number]},
            'yaxis': {'autorange': 'reversed'},
        }

        if data[labels_checkbox]:

            labels_x = []
            labels_y = []
            labels_z = []
            labels_text = []

            for label in map_file.Labels:
                if label.Size >= data[labels_size_threshold_number]:
                    max_height = -1
                    x = label.X
                    y = label.Y
                    for dx in dock(x, map_file.Width-1):
                        for dy in dock(y, map_file.Height-1):
                            max_height = max(max_height, map_file.HeightMap[dy, dx])
                    labels_x.append(x)
                    labels_y.append(y)
                    labels_z.append(max_height)
                    labels_text.append(label.Name)

            scene["annotations"] = [
                dict(
                    showarrow=False,
                    x=x,
                    y=y,
                    z=z,
                    text=text,
                    xanchor="left",
                    xshift=10,
                    opacity=0.7,
                    bgcolor="white"
                )
                for x, y, z, text in zip(labels_x, labels_y, labels_z, labels_text)
            ]

        fig.update_layout(scene=scene, showlegend=False)

        return {output_plot: fig}

    plot_button.click(plot, {file_input, sub_file_input, code_dropdown,
                             labels_checkbox, labels_size_threshold_number, 
                             path_checkbox, road_checkbox, pike_checkbox, railway_checkbox,
                             elevation_scale_number, road_offset_number}, {output_plot})
    # plot_button.click(lambda data: {output_img: test()}, {file_input, path_checkbox, road_checkbox, pike_checkbox, plot_button}, {output_img})

if __name__ == "__main__":
    demo.launch()