zasheza commited on
Commit
8bb35f9
1 Parent(s): ec8ea2c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -131
app.py CHANGED
@@ -1,147 +1,107 @@
1
- import io
2
- import random
3
- from typing import List, Tuple
4
-
5
- import aiohttp
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
- @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
- 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
- class_items = class_names.split(",")
79
- class_likelihoods = get_similarity_scores(class_items, pil_img)
80
-
81
- # build the results column
82
- results = pn.Column("##### 🎉 Here are the results!", img)
83
-
84
- for class_item, class_likelihood in zip(class_items, class_likelihoods):
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
- # 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 vega_datasets
 
 
 
 
2
  import panel as pn
3
+ import pandas as pd
4
+ import altair as alt
5
+ from vega_datasets import data
6
+
7
 
8
+ pn.extension(design='bootstrap')
9
 
10
+ # we want to use vega, tell Panel to load up what we need
11
+ pn.extension('vega')
 
 
 
 
 
12
 
13
 
14
+ template = pn.template.BootstrapTemplate(
15
+ title='SI649 Lab7 Viz4',
16
+ )
 
 
 
17
 
18
 
19
+ # Import panel and vega datasets
20
+ # load data
21
+ df1 = pd.read_csv(
22
+ "https://raw.githubusercontent.com/dallascard/SI649_public/main/altair_hw3/approval_polllist.csv")
23
+ df2 = pd.read_csv(
24
+ "https://raw.githubusercontent.com/dallascard/SI649_public/main/altair_hw3/approval_topline.csv")
 
25
 
26
+ # Enable Panel extensions
27
+ pn.extension()
28
 
29
+ # Define a function to create and return a plot
 
 
 
30
 
31
 
32
+ def create_plot(subgroup, date_range, moving_av_window):
33
+
34
+ # Apply any required transformations to the data in pandas
35
+ # print(pd.to_datetime(df2['timestamp']), type(date_range[0]))
36
+
37
+ # df2_filtered = df2[(df2['subgroup'] == subgroup) & (df2['timestamp'] >= date_range[0]) & (df2['timestamp'] <= date_range[1])]
38
+ df2_filtered = df2[(df2['subgroup'] == subgroup) & (df2['timestamp'] >= pd.Timestamp(
39
+ date_range[0])) & (df2['timestamp'] <= pd.Timestamp(date_range[1]))]
40
+
41
+ # Calculate the moving average
42
+ # df2_filtered['moving_rate'] = df2_filtered['rate'].rolling(window=moving_av_window).mean()
43
+ df2_filtered['moving_rate'] = df2_filtered['rate'].rolling(
44
+ window=moving_av_window).mean().shift(-moving_av_window//2)
45
+ # df2_filtered.loc[:, 'moving_rate'] = df2_filtered['rate'].rolling(window=moving_av_window).mean()
46
+ #
47
+ # Line chart for moving average with df2_filtered
48
+ line = alt.Chart(df2_filtered).mark_line().encode(
49
+ x='timestamp:T',
50
+ y='moving_rate:Q',
51
+ color=alt.value('red')
52
+ ).transform_filter(
53
+ # keep only approved polls
54
+ alt.FieldOneOfPredicate(field='choice', oneOf=['approve'])
55
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ # Scatter plot with individual polls
58
+ scatter = alt.Chart(df2_filtered).mark_circle().encode(
59
+ x='timestamp:T',
60
+ y='rate:Q',
61
+ color=alt.value('gray'),
62
+ opacity=alt.value(0.7),
63
+ tooltip=['timestamp:T', 'rate:Q'],
64
+ size=alt.value(10)
65
+ ).transform_filter(
66
+ # keep only approved polls
67
+ alt.FieldOneOfPredicate(field='choice', oneOf=['approve'])
68
+ )
69
 
70
+ # Put them together
71
+ plot = scatter + line
72
+ # change y axis range of the plot to 30 to 60
 
 
73
 
74
+ # plot = plot + line
75
+ plot = plot.properties(title="Approval Ratings for Joe Biden")
76
+ plot = plot.encode(
77
+ y=alt.Y('rate:Q', scale=alt.Scale(domain=[30, 60]))
78
+ )
79
+ # Return the combined chart
80
+ return plot
81
+
82
+
83
+ # Create the selection widget using subgroup column
84
+ selection_subgroup = pn.widgets.Select(
85
+ name='Subgroup', options=df2.subgroup.unique().tolist())
86
+
87
+ # Create the slider for the date range
88
+ # df2['timestamp'] = pd.to_datetime(df2['timestamp'])
89
+ date_range_slider = pn.widgets.DateRangeSlider(name='Date Range', start=df2.timestamp.min(
90
+ ), end=df2.timestamp.max(), value=(df2.timestamp.min(), df2.timestamp.max()))
91
+
92
+ # Create the slider for the moving average window
93
+ moving_av_window_slider = pn.widgets.IntSlider(
94
+ name='Moving Average Window', start=1, end=30, step=1, value=1)
95
+ # Bind the widgets to the create_plot function
96
+ create_plot_wgt = pn.bind(create_plot, subgroup=selection_subgroup,
97
+ date_range=date_range_slider, moving_av_window=moving_av_window_slider)
98
+
99
+ # Combine everything in a Panel Column to create an app
100
+ main_col = pn.Column(
101
+ create_plot_wgt,
102
+ selection_subgroup,
103
+ date_range_slider,
104
+ moving_av_window_slider,
105
  )
106
+ # set the app to be servable
107
+ main_col.servable()