Paste Question 4 for Lab 7
Browse filesDeploy an interactive chart for the moving average of the approval rate for Joe Biden
app.py
CHANGED
@@ -1,147 +1,66 @@
|
|
1 |
-
import io
|
2 |
-
import random
|
3 |
-
from typing import List, Tuple
|
4 |
-
|
5 |
-
import aiohttp
|
6 |
import panel as pn
|
7 |
-
|
8 |
-
from transformers import CLIPModel, CLIPProcessor
|
9 |
-
|
10 |
-
pn.extension(design="bootstrap", sizing_mode="stretch_width")
|
11 |
-
|
12 |
-
ICON_URLS = {
|
13 |
-
"brand-github": "https://github.com/holoviz/panel",
|
14 |
-
"brand-twitter": "https://twitter.com/Panel_Org",
|
15 |
-
"brand-linkedin": "https://www.linkedin.com/company/panel-org",
|
16 |
-
"message-circle": "https://discourse.holoviz.org/",
|
17 |
-
"brand-discord": "https://discord.gg/AXRHnJU6sP",
|
18 |
-
}
|
19 |
-
|
20 |
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
@pn.cache
|
30 |
-
def load_processor_model(
|
31 |
-
processor_name: str, model_name: str
|
32 |
-
) -> Tuple[CLIPProcessor, CLIPModel]:
|
33 |
-
processor = CLIPProcessor.from_pretrained(processor_name)
|
34 |
-
model = CLIPModel.from_pretrained(model_name)
|
35 |
-
return processor, model
|
36 |
|
|
|
37 |
|
38 |
-
|
39 |
-
async with aiohttp.ClientSession() as session:
|
40 |
-
async with session.get(image_url) as resp:
|
41 |
-
return Image.open(io.BytesIO(await resp.read()))
|
42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
|
44 |
-
|
45 |
-
|
46 |
-
|
|
|
47 |
)
|
48 |
-
inputs = processor(
|
49 |
-
text=class_items,
|
50 |
-
images=[image],
|
51 |
-
return_tensors="pt", # pytorch tensors
|
52 |
-
)
|
53 |
-
outputs = model(**inputs)
|
54 |
-
logits_per_image = outputs.logits_per_image
|
55 |
-
class_likelihoods = logits_per_image.softmax(dim=1).detach().numpy()
|
56 |
-
return class_likelihoods[0]
|
57 |
|
|
|
|
|
|
|
|
|
|
|
58 |
|
59 |
-
|
60 |
-
|
61 |
-
High level function that takes in the user inputs and returns the
|
62 |
-
classification results as panel objects.
|
63 |
-
"""
|
64 |
-
try:
|
65 |
-
main.disabled = True
|
66 |
-
if not image_url:
|
67 |
-
yield "##### ⚠️ Provide an image URL"
|
68 |
-
return
|
69 |
-
|
70 |
-
yield "##### ⚙ Fetching image and running model..."
|
71 |
-
try:
|
72 |
-
pil_img = await open_image_url(image_url)
|
73 |
-
img = pn.pane.Image(pil_img, height=400, align="center")
|
74 |
-
except Exception as e:
|
75 |
-
yield f"##### 😔 Something went wrong, please try a different URL!"
|
76 |
-
return
|
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 |
-
class_names = pn.widgets.TextInput(
|
109 |
-
name="Comma separated class names",
|
110 |
-
placeholder="Enter possible class names, e.g. cat, dog",
|
111 |
-
value="cat, dog, parrot",
|
112 |
-
)
|
113 |
-
|
114 |
-
input_widgets = pn.Column(
|
115 |
-
"##### 😊 Click randomize or paste a URL to start classifying!",
|
116 |
-
pn.Row(image_url, randomize_url),
|
117 |
-
class_names,
|
118 |
-
)
|
119 |
-
|
120 |
-
# add interactivity
|
121 |
-
interactive_result = pn.panel(
|
122 |
-
pn.bind(process_inputs, image_url=image_url, class_names=class_names),
|
123 |
-
height=600,
|
124 |
-
)
|
125 |
-
|
126 |
-
# add footer
|
127 |
-
footer_row = pn.Row(pn.Spacer(), align="center")
|
128 |
-
for icon, url in ICON_URLS.items():
|
129 |
-
href_button = pn.widgets.Button(icon=icon, width=35, height=35)
|
130 |
-
href_button.js_on_click(code=f"window.open('{url}')")
|
131 |
-
footer_row.append(href_button)
|
132 |
-
footer_row.append(pn.Spacer())
|
133 |
-
|
134 |
-
# create dashboard
|
135 |
-
main = pn.WidgetBox(
|
136 |
-
input_widgets,
|
137 |
-
interactive_result,
|
138 |
-
footer_row,
|
139 |
-
)
|
140 |
-
|
141 |
-
title = "Panel Demo - Image Classification"
|
142 |
-
pn.template.BootstrapTemplate(
|
143 |
-
title=title,
|
144 |
-
main=main,
|
145 |
-
main_max_width="min(50%, 698px)",
|
146 |
-
header_background="#F08080",
|
147 |
-
).servable(title=title)
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import panel as pn
|
2 |
+
import vega_datasets
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
+
# Enable Panel extensions
|
5 |
+
pn.extension(design='bootstrap')
|
6 |
+
pn.extension('vega')
|
7 |
+
template = pn.template.BootstrapTemplate(
|
8 |
+
title='Nan-Hsin Lin',
|
9 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
+
# Define a function to create and return a plot
|
12 |
|
13 |
+
def create_plot(subgroup, date_range, moving_av_window):
|
|
|
|
|
|
|
14 |
|
15 |
+
# Apply any required transformations to the data in pandas
|
16 |
+
df3 = df2[df2['choice'] == 'approve'].copy()
|
17 |
+
df3 = df3[df3['subgroup'] == subgroup]
|
18 |
+
df3['smoothed_rate'] = df3['rate'].rolling(moving_av_window).mean().shift(-int(moving_av_window/2))
|
19 |
+
start_date, end_date = date_range
|
20 |
+
df3 = df3[(df3['timestamp'] >= np.datetime64(start_date)) & (df3['timestamp'] <= np.datetime64(end_date))]
|
21 |
|
22 |
+
# Line chart
|
23 |
+
rate_line = alt.Chart(df3).mark_line(strokeWidth=2, color='red').encode(
|
24 |
+
x=alt.X('timestamp:T', axis=alt.Axis(title=None)),
|
25 |
+
y=alt.Y('average(smoothed_rate):Q', axis=alt.Axis(title='move_avg'), scale=alt.Scale(domain=[30, 60]))
|
26 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
+
# Scatter plot with individual polls
|
29 |
+
rate_scatter = alt.Chart(df3).mark_point(color='grey', size=2, opacity=0.7).encode(
|
30 |
+
x=alt.X('timestamp:T', axis=alt.Axis(title=None)),
|
31 |
+
y=alt.Y('average(rate):Q', axis=alt.Axis(title='approve'), scale=alt.Scale(domain=[30, 60])),
|
32 |
+
)
|
33 |
|
34 |
+
# Put them together
|
35 |
+
plot = alt.layer(rate_line, rate_scatter).configure_view(strokeWidth=0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
|
37 |
+
# Return the combined chart
|
38 |
+
return plot
|
39 |
+
|
40 |
+
# Create the selection widget
|
41 |
+
select = pn.widgets.Select(name='Select', options=df2['subgroup'].unique().tolist())
|
42 |
+
|
43 |
+
# Create the slider for the date range
|
44 |
+
dateSlider = pn.widgets.DateRangeSlider(name='Date Range Slider',
|
45 |
+
start=df2['timestamp'].min(),
|
46 |
+
end=df2['timestamp'].max(),
|
47 |
+
value=(df2['timestamp'].min(), df2['timestamp'].max()))
|
48 |
+
|
49 |
+
# Create the slider for the moving average window
|
50 |
+
avgSlider = pn.widgets.IntSlider(name='Moving average window', start=1, end=100, value=1)
|
51 |
+
|
52 |
+
# Bind the widgets to the create_plot function
|
53 |
+
plot_widgets = pn.Row(pn.bind(create_plot, select, dateSlider, avgSlider))
|
54 |
+
|
55 |
+
# Combine everything in a Panel Column to create an app
|
56 |
+
maincol = pn.Column()
|
57 |
+
maincol.append("# SI649 Lab07")
|
58 |
+
maincol.append("Hello! This is **Nan**. I love information visualization! Email me: [[email protected]](mailto:[email protected])")
|
59 |
+
maincol.append(plot_widgets)
|
60 |
+
maincol.append(select)
|
61 |
+
maincol.append(dateSlider)
|
62 |
+
maincol.append(avgSlider)
|
63 |
+
template.main.append(maincol)
|
64 |
+
|
65 |
+
# set the app to be servable
|
66 |
+
template.servable(title="Nan-Hsin Lin")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|