-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
227 lines (186 loc) · 7.45 KB
/
app.py
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# main app
# >>> streamlit run app.py
import pandas as pd
import numpy as np
import streamlit as st
import streamlit.components.v1 as components
import altair as alt
import networkx as nx
from pyvis.network import Network
from param import col_dict, snames, max_node_map, def_node_map
from util import parse_data, parse_ts, clock, rc
#####################
### INITIAL SETUP ###
#####################
# styling
st.set_page_config(page_title='TrekViz', page_icon="🖖")
st.markdown(""" <style>
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
</style> """, unsafe_allow_html=True)
padding = 0
st.markdown(f""" <style>
.reportview-container .main .block-container{{
padding-top: {padding}rem;
padding-right: {padding}rem;
padding-left: {padding}rem;
padding-bottom: {padding}rem;
}} </style> """, unsafe_allow_html=True)
st.sidebar.markdown('# STAR TREK VIZUALISER')
# for selecting series
series_pick = st.sidebar.selectbox('Select series:',
list(snames.values()),
key='series', index=1)
snames_r = {v: k for k, v in snames.items()}
series_code = snames_r[series_pick] # for later use
# initial parse data
df, chars, relationships = parse_data(series_code)
chars_sorted = np.sort(chars) # for ordered dropbox
###########################
#### INTERACTIONS CHART ###
###########################
# define options in sidebar
st.sidebar.markdown('## NETWORK OPTIONS')
physics_bool = st.sidebar.checkbox(
'Add physics engine', key='phys', value=False)
box_bool = st.sidebar.checkbox('Make nodes boxes', key='boxb', value=True)
col_bool = st.sidebar.checkbox('Random colors', key='colb', value=False)
max_node = max_node_map[series_code]
default_node = def_node_map[series_code]
interactions = st.sidebar.slider(
label="Number of Nodes",
min_value=4,
max_value=max_node,
step=4,
value=default_node)
st.markdown(
'''#### INTERACTION NETWORK
Wider lines = more interactions.
Click and drag nodes to rearrange the network.
''')
nx_graph = nx.empty_graph(interactions) # create initial dummy graph
chars_subset = chars[:interactions] # select characer subset
# positions depend on number of interactions
clockface = clock[interactions]
pos_dict = {chars[i]: clockface[i]
for i in range(interactions)} # positions for character
name2node = {} # for mapping from node idx to character name
# add each character node
for idx, c in enumerate(chars_subset):
name2node[c] = idx
for k, v in {'label': c,
'mass': 10,
'physics': physics_bool,
'x': (pos_dict[c][0]) * 1.6 * 500,
'y': (pos_dict[c][1]) * 1.1 * 500,
'size': 20,
'shape': 'box' if box_bool else 'dot',
'color': f'rgb({rc()},{rc()},{rc()})' if col_bool
else col_dict[series_code][c]
}.items():
nx_graph.nodes[idx][k] = v
# # NON-FUNCTIONAL CODE to add thumbnail images (used to create and save interactions with thumbnails)
# c2 = c.replace("'",'')
# ipath = f'../../thumbnails/{series_code}/{c2}.png'
# nx_graph.nodes[idx]['image'] = ipath
# nx_graph.nodes[idx]['shape'] = 'image'
# nx_graph.nodes[idx]['label'] = ' '
# nx_graph.nodes[idx]['size'] = 30
# DOES NOT WORK BECAUSE STREAMLIT HMTL CANNOT READ FROM DIRECTORY
# HOPEFULLY SOLVED IN FUTURE RELEASE?
constant_dict = {'TOSm': 40, 'TNGm': 20, 'JJA': 30}
constant = constant_dict.get(series_code, 300)
# add each interaction edge
for wt, fr, to in relationships.values:
if (to in chars_subset) & (fr in chars_subset) & (fr != to):
if wt > 0:
nx_graph.add_edge(name2node[fr], name2node[to],
width=wt / constant,
color='rgb(100,100,100)')
# translate to pyvis network
h, w = 500, 750
nt = Network(f'{h}px', f'{w}px',
font_color='white' if box_bool else 'black')
nt.from_nx(nx_graph)
path = f'network.html'
nt.show(path)
HtmlFile = open(path, 'r') # , encoding='utf-8')
source_code = HtmlFile.read()
components.html(source_code, height=h * 1.1, width=w * 1.1)
##########################
#### TIME SERIES CHART ###
##########################
st.sidebar.markdown('### TIME-SERIES OPTIONS')
st.markdown(
'''#### TIME-SERIES
Click on the legend to view one time-series only.
Double click on the graph to reset the view.
''')
# for switching to season averages
if series_code in ['ENT', 'TOS', 'TNG', 'VOY', 'DS9']:
season_bool = st.sidebar.checkbox(
'Season average', key='check', value=False)
xlab = 'Season' if season_bool else 'Episode'
ylab = 'Lines per Episode' if season_bool else 'Lines'
tool1 = 'Season'
else:
season_bool = False
xlab = 'Movie'
ylab = 'Lines'
tool1 = 'Movie'
# for selecting characters
char_pick1 = st.sidebar.selectbox(label='Select first character:',
options=chars_sorted, key='char1',
index=int(np.argmax(chars_sorted == chars[0])))
char_pick2 = st.sidebar.selectbox(label='Select second character:',
options=chars_sorted, key='char2',
index=int(np.argmax(chars_sorted == chars[1])))
# parse data for ts
line_count, ilabel = parse_ts(
df, season_bool, xlab, ylab, char_pick1, char_pick2)
# for updating graph based on legend selection
selection = alt.selection_single(encodings=['color'], bind='legend')
color = alt.condition(selection,
alt.Color('Character:N', legend=None),
alt.value('lightgray')
)
# main chart code
ts_chart = alt.Chart(line_count, width=750, height=500).encode(
alt.Y(ylab,
scale=alt.Scale(paddingOuter=0.1)
),
alt.X(xlab + ' Number',
axis=alt.Axis(tickMinStep=1),
scale=alt.Scale(paddingInner=1)
),
color=alt.Color('Character',
legend=alt.Legend(
orient="top", title=None, labelLimit=300),
sort=[char_pick1, char_pick2],
scale=alt.Scale(
domain=[char_pick1, char_pick2, ilabel],
range=['rgb(150,20,150)', 'rgb(150,100,0)', 'rgb(70,70,100)'])
),
tooltip=[xlab, tool1, "Character", ylab]
).add_selection(selection).transform_filter(selection).interactive()
# add to app
st.altair_chart(ts_chart.mark_line(color='firebrick', point=True))
st.markdown(
'''
#### NOTES
* Interactions = the number of consecutive lines the two characters shared.
* Transcripts of episodes were used, hence "Episode Number" is actually transcript number.
* Some transcripts covered 2-parters, hence why there are less transcripts that aired episodes.
* Recent series (Discovery, Picard, Lower Decks) are not included due to lack of online transcripts.
''')
###############
#### ABOUT ####
###############
st.sidebar.markdown('''
## ABOUT
Code: [source](https://github.com/gmorinan/trekviz)\n
Author: [profile](https://www.linkedin.com/in/gmorinan/) / [words](https://medium.com/@g.morinan)\n
Transcripts source: [chakoteya.net](http://www.chakoteya.net/)\n
StarTrek rights owner: [ViacomCBS](https://www.viacomcbs.com/)\n
Tools: [Streamlit](https://streamlit.io/), [Altair](https://altair-viz.github.io/), [Networkx](https://networkx.org/) & [Pyvis](https://pyvis.readthedocs.io/en/latest/)
''')