Update to turing.py
Browse files
app.py
CHANGED
@@ -1,147 +1,244 @@
|
|
1 |
-
import
|
2 |
-
import
|
3 |
-
|
4 |
-
|
5 |
-
import
|
6 |
import panel as pn
|
7 |
-
from PIL import Image
|
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 |
-
async def random_url(_):
|
22 |
-
pet = random.choice(["cat", "dog"])
|
23 |
-
api_url = f"https://api.the{pet}api.com/v1/images/search"
|
24 |
-
async with aiohttp.ClientSession() as session:
|
25 |
-
async with session.get(api_url) as resp:
|
26 |
-
return (await resp.json())[0]["url"]
|
27 |
|
28 |
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
model = CLIPModel.from_pretrained(model_name)
|
35 |
-
return processor, model
|
36 |
|
37 |
-
|
38 |
-
async def open_image_url(image_url: str) -> Image:
|
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 |
-
def get_similarity_scores(class_items: List[str], image: Image) -> List[float]:
|
45 |
-
processor, model = load_processor_model(
|
46 |
-
"openai/clip-vit-base-patch32", "openai/clip-vit-base-patch32"
|
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 |
-
async def process_inputs(class_names: List[str], image_url: str):
|
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 |
-
class_likelihoods = get_similarity_scores(class_items, pil_img)
|
80 |
|
81 |
-
|
82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
|
84 |
-
|
85 |
-
row_label = pn.widgets.StaticText(
|
86 |
-
name=class_item.strip(), value=f"{class_likelihood:.2%}", align="center"
|
87 |
-
)
|
88 |
-
row_bar = pn.indicators.Progress(
|
89 |
-
value=int(class_likelihood * 100),
|
90 |
-
sizing_mode="stretch_width",
|
91 |
-
bar_color="secondary",
|
92 |
-
margin=(0, 10),
|
93 |
-
design=pn.theme.Material,
|
94 |
-
)
|
95 |
-
results.append(pn.Column(row_label, row_bar))
|
96 |
-
yield results
|
97 |
-
finally:
|
98 |
-
main.disabled = False
|
99 |
-
|
100 |
-
|
101 |
-
# create widgets
|
102 |
-
randomize_url = pn.widgets.Button(name="Randomize URL", align="end")
|
103 |
-
|
104 |
-
image_url = pn.widgets.TextInput(
|
105 |
-
name="Image URL to classify",
|
106 |
-
value=pn.bind(random_url, randomize_url),
|
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 |
-
|
121 |
-
|
122 |
-
pn.bind(process_inputs, image_url=image_url, class_names=class_names),
|
123 |
-
height=600,
|
124 |
-
)
|
125 |
|
126 |
-
#
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
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 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import pandas as pd
|
4 |
+
from collections import defaultdict, Counter
|
5 |
+
import altair as alt
|
6 |
import panel as pn
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
|
9 |
+
def choices_to_df(choices, hue):
|
10 |
+
df = pd.DataFrame(choices, columns=['choices'])
|
11 |
+
df['hue'] = hue
|
12 |
+
df['hue'] = df['hue'].astype(str)
|
13 |
+
return df
|
|
|
|
|
14 |
|
15 |
+
def arrange_data():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
17 |
+
# Human Data
|
|
|
18 |
|
19 |
+
df = pd.read_csv('Project/2_scientific/ChatGPT-Behavioral-main/data/bomb_risk.csv')
|
20 |
+
df = df[df['Role'] == 'player']
|
21 |
+
df = df[df['gameType'] == 'bomb_risk']
|
22 |
+
df.sort_values(by=['UserID', 'Round'])
|
23 |
+
|
24 |
+
prefix_to_choices_human = defaultdict(list)
|
25 |
+
prefix_to_IPW = defaultdict(list)
|
26 |
+
prev_user = None
|
27 |
+
prev_move = None
|
28 |
+
prefix = ''
|
29 |
+
bad_user = False
|
30 |
+
for _, row in df.iterrows():
|
31 |
+
if bad_user: continue
|
32 |
+
if row['UserID'] != prev_user:
|
33 |
+
prev_user = row['UserID']
|
34 |
+
prefix = ''
|
35 |
+
bad_user = False
|
36 |
+
|
37 |
+
move = row['move']
|
38 |
+
if move < 0 or move > 100:
|
39 |
+
bad_users = True
|
40 |
+
continue
|
41 |
+
prefix_to_choices_human[prefix].append(move)
|
42 |
+
|
43 |
+
if len(prefix) == 0:
|
44 |
+
prefix_to_IPW[prefix].append(1)
|
45 |
+
elif prefix[-1] == '1':
|
46 |
+
prev_move = min(prev_move, 98)
|
47 |
+
prefix_to_IPW[prefix].append(1./(100 - prev_move))
|
48 |
+
elif prefix[-1] == '0':
|
49 |
+
prev_move = max(prev_move, 1)
|
50 |
+
prefix_to_IPW[prefix].append(1./(prev_move))
|
51 |
+
else: assert False
|
52 |
+
|
53 |
+
prev_move = move
|
54 |
+
|
55 |
+
prefix += '1' if row['roundResult'] == 'SAFE' else '0'
|
56 |
+
|
57 |
+
|
58 |
+
# Model Data
|
59 |
+
|
60 |
+
prefix_to_choices_model = defaultdict(lambda : defaultdict(list))
|
61 |
+
for model in ['ChatGPT-4', 'ChatGPT-3']:
|
62 |
+
if model == 'ChatGPT-4':
|
63 |
+
file_names = [
|
64 |
+
'bomb_gpt4_2023_05_15-12_13_51_AM.json'
|
65 |
+
]
|
66 |
+
elif model == 'ChatGPT-3':
|
67 |
+
file_names = [
|
68 |
+
'bomb_turbo_2023_05_14-10_45_50_PM.json'
|
69 |
+
]
|
70 |
+
|
71 |
+
choices = []
|
72 |
+
scenarios = []
|
73 |
+
for file_name in file_names:
|
74 |
+
with open(os.path.join('Project/2_scientific/ChatGPT-Behavioral-main/records', file_name), 'r') as f:
|
75 |
+
records = json.load(f)
|
76 |
+
choices += records['choices']
|
77 |
+
scenarios += records['scenarios']
|
78 |
+
|
79 |
+
assert len(scenarios) == len(choices)
|
80 |
+
print('loaded %i valid records' % len(scenarios))
|
81 |
+
|
82 |
+
prefix_to_choice = defaultdict(list)
|
83 |
+
prefix_to_result = defaultdict(list)
|
84 |
+
prefix_to_pattern = defaultdict(Counter)
|
85 |
+
wrong_sum = 0
|
86 |
+
for scenarios_tmp, choices_tmp in zip(scenarios, choices):
|
87 |
+
|
88 |
+
result = 0
|
89 |
+
for i, scenario in enumerate(scenarios_tmp):
|
90 |
+
prefix = tuple(scenarios_tmp[:i])
|
91 |
+
prefix = ''.join([str(x) for x in prefix])
|
92 |
+
choice = choices_tmp[i]
|
93 |
+
|
94 |
+
prefix_to_choice[prefix].append(choice)
|
95 |
+
prefix_to_pattern[prefix][tuple(choices_tmp[:-1])] += 1
|
96 |
+
|
97 |
+
prefix = tuple(scenarios_tmp[:i+1])
|
98 |
+
if scenario == 1:
|
99 |
+
result += choice
|
100 |
+
prefix_to_result[prefix].append(result)
|
101 |
+
|
102 |
+
print('# of wrong sum:', wrong_sum)
|
103 |
+
print('# of correct sum:', len(scenarios) - wrong_sum)
|
104 |
+
|
105 |
+
prefix_to_choices_model[model] = prefix_to_choice
|
106 |
+
|
107 |
+
|
108 |
+
# Arrange Data
|
109 |
+
|
110 |
+
round_dict = {'': [1, -1, -1],
|
111 |
+
'0': [2, 0, -1],
|
112 |
+
'1': [2, 1, -1],
|
113 |
+
'00': [3, 0, 0],
|
114 |
+
'01': [3, 0, 1],
|
115 |
+
'10': [3, 1, 0],
|
116 |
+
'11': [3, 1, 1]}
|
117 |
+
|
118 |
+
df_bomb_all = pd.DataFrame()
|
119 |
+
|
120 |
+
for prefix in round_dict:
|
121 |
+
|
122 |
+
df_bomb_human = choices_to_df(prefix_to_choices_human[prefix], hue='Human')
|
123 |
+
df_bomb_human['weight'] = prefix_to_IPW[prefix]
|
124 |
+
|
125 |
+
df_bomb_models = pd.concat([choices_to_df(
|
126 |
+
prefix_to_choices_model[model][prefix], hue=model
|
127 |
+
) for model in prefix_to_choices_model]
|
128 |
+
)
|
129 |
+
df_bomb_models['weight'] = 1
|
130 |
+
|
131 |
+
df_bomb_temp = pd.concat([df_bomb_human, df_bomb_models])
|
132 |
+
df_bomb_temp['prefix'] = prefix
|
133 |
+
|
134 |
+
df_bomb_all = pd.concat([df_bomb_all, df_bomb_temp])
|
135 |
+
|
136 |
+
df_density = df_bomb_all.groupby(['hue', 'prefix'])['choices'].value_counts(normalize=True).unstack(fill_value=0).stack().reset_index()
|
137 |
+
df_density = df_density.rename(columns={'hue': 'Subject', 'choices': 'Boxes', 0: 'Density'})
|
138 |
+
df_density['Round'] = df_density['prefix'].apply(lambda x: round_dict[x][0])
|
139 |
|
140 |
+
return df_density
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
141 |
|
|
|
|
|
|
|
|
|
|
|
142 |
|
143 |
+
df_density = arrange_data()
|
144 |
+
alt.data_transformers.disable_max_rows()
|
|
|
|
|
|
|
145 |
|
146 |
+
# Enable Panel extensions
|
147 |
+
pn.extension(design='bootstrap')
|
148 |
+
pn.extension('vega')
|
149 |
+
template = pn.template.BootstrapTemplate(
|
150 |
+
title='Nan-Hsin Lin | SI649 Scientific Viz Project',
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
151 |
)
|
152 |
|
153 |
+
# Define a function to create and return a plot
|
154 |
+
def create_plot(bomb_1, bomb_2):
|
155 |
+
|
156 |
+
bomb_1 = int(not bomb_1)
|
157 |
+
bomb_2 = int(not bomb_2)
|
158 |
+
|
159 |
+
selection = alt.selection_single(encodings=['color'], empty='none', value=3)
|
160 |
+
opacityCondition = alt.condition(selection, alt.value(1), alt.value(0.3))
|
161 |
+
range_ = ['#009FB7', '#FED766', '#FE4A49']
|
162 |
+
|
163 |
+
plot = alt.Chart(df_density).transform_filter(
|
164 |
+
(alt.datum.prefix == '') | (alt.datum.prefix == str(bomb_1)) | (alt.datum.prefix == str(bomb_1) + str(bomb_2))
|
165 |
+
).mark_bar(opacity=0.5).encode(
|
166 |
+
x=alt.X('Boxes:Q',
|
167 |
+
bin=alt.Bin(maxbins=10),
|
168 |
+
title='Number of boxes opened',
|
169 |
+
axis=alt.Axis(ticks=False,
|
170 |
+
labelFontSize=11,
|
171 |
+
labelColor='#AAA7AD',
|
172 |
+
titleFontSize=12,
|
173 |
+
titleColor='#AAA7AD',
|
174 |
+
domain=False)),
|
175 |
+
y=alt.Y('Density:Q',
|
176 |
+
stack=None,
|
177 |
+
scale=alt.Scale(domain=[0, 1]),
|
178 |
+
axis=alt.Axis(format='.0%',
|
179 |
+
ticks=False,
|
180 |
+
tickCount=5,
|
181 |
+
labelFontSize=11,
|
182 |
+
labelColor='#AAA7AD',
|
183 |
+
titleFontSize=12,
|
184 |
+
titleColor='#AAA7AD',
|
185 |
+
domain=False,
|
186 |
+
grid=False)),
|
187 |
+
color=alt.Color('Round:N',
|
188 |
+
scale=alt.Scale(domain=[1, 2, 3], range=range_)),
|
189 |
+
row=alt.Row('Subject:N',
|
190 |
+
header=alt.Header(title=None, orient='top', labelFontSize=16),
|
191 |
+
sort='descending'),
|
192 |
+
tooltip=['Subject:N', 'Round:N', 'Boxes:Q', alt.Tooltip('Density:Q', format='.0%')]
|
193 |
+
).properties(width=400, height=150
|
194 |
+
).configure_view(strokeWidth=3, stroke='lightgrey'
|
195 |
+
).configure_legend(
|
196 |
+
titleFontSize=12,
|
197 |
+
titleColor='#AAA7AD',
|
198 |
+
titleAnchor='middle',
|
199 |
+
titlePadding=8,
|
200 |
+
labelFontSize=12,
|
201 |
+
labelColor='#AAA7AD',
|
202 |
+
labelFontWeight='bold',
|
203 |
+
symbolOffset=20,
|
204 |
+
orient='none',
|
205 |
+
direction='horizontal',
|
206 |
+
legendX=120,
|
207 |
+
legendY=-90,
|
208 |
+
symbolSize=200
|
209 |
+
).add_selection(selection).encode(
|
210 |
+
opacity=opacityCondition
|
211 |
+
)
|
212 |
+
|
213 |
+
return plot
|
214 |
+
|
215 |
+
# Create widgets
|
216 |
+
switch_1 = pn.widgets.Switch(name='Bomb in Round 1', value=True)
|
217 |
+
switch_2 = pn.widgets.Switch(name='Bomb in Round 2', value=True)
|
218 |
+
|
219 |
+
plot_widgets = pn.bind(create_plot, switch_1, switch_2)
|
220 |
+
|
221 |
+
# Combine everything in a Panel Column to create an app
|
222 |
+
maincol = pn.Column()
|
223 |
+
maincol.append(pn.Row(pn.layout.HSpacer(),
|
224 |
+
"### A Turing test of whether AI chatbots are behaviorally similar to humans",
|
225 |
+
pn.layout.HSpacer()))
|
226 |
+
maincol.append(pn.Row(pn.Spacer(width=100)))
|
227 |
+
maincol.append(pn.Row(pn.layout.HSpacer(),
|
228 |
+
"#### Bomb Risk Game: Human vs. ChatGPT-4 vs. ChatGPT-3",
|
229 |
+
pn.layout.HSpacer()))
|
230 |
+
maincol.append(pn.Row(pn.layout.HSpacer(),
|
231 |
+
"Bomb in Round 1", switch_1,
|
232 |
+
pn.Spacer(width=50),
|
233 |
+
"Bomb in Round 2", switch_2,
|
234 |
+
pn.layout.HSpacer()))
|
235 |
+
maincol.append(pn.Row(pn.layout.HSpacer(),
|
236 |
+
plot_widgets,
|
237 |
+
pn.layout.HSpacer()))
|
238 |
+
maincol.append(pn.Row(pn.layout.HSpacer(),
|
239 |
+
"**Fig 5.** ChatGPT-4 and ChatGPT-3 act as if they have particular risk preferences. Both have the same mode as human distribution in the first round or when experiencing favorable outcomes in the Bomb Risk Game. When experiencing negative outcomes, ChatGPT-4 remains consistent and risk-neutral, while ChatGPT-3 acts as if it becomes more risk-averse.",
|
240 |
+
pn.layout.HSpacer()))
|
241 |
+
template.main.append(maincol)
|
242 |
+
|
243 |
+
# set the app to be servable
|
244 |
+
template.servable(title="SI649 Scientific Viz Project")
|