FernandoPythonDev commited on
Commit
d009c34
·
1 Parent(s): ccceb9b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -137
app.py CHANGED
@@ -1,147 +1,138 @@
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
+ # Importing the useful libraries and modules
2
+ import pandas as pd
3
+ import numpy as np
 
 
4
  import panel as pn
5
+ import hvplot.pandas
6
+
7
+ pn.extension("tabulator")
8
+
9
+ # -------------- Load the data -----------------------------
10
+ data = pd.read_csv("clean_data.csv")
11
+
12
+ # -------------- Make DataFrame Pipeline Interactive -----------
13
+ idf = data.interactive()
14
+
15
+ # ------------- CO2 emission over time by continent Plot ------------------
16
+
17
+ # Year Slider
18
+ year_slider = pn.widgets.IntSlider(name="Year slider", start=1750, end=2020, step=5, value=1850)
19
+
20
+ # Radio Buttons for CO2 Measures
21
+ yaxis_co2 = pn.widgets.RadioButtonGroup(
22
+ name="Y axis",
23
+ options=["co2", "co2_per_capita",],
24
+ button_type="success"
25
+ )
26
+
27
+ # Y-axis Options
28
+ yaxis_co2_source = pn.widgets.RadioButtonGroup(
29
+ name="Y axis",
30
+ options=["coal_co2", "oil_co2", "gas_co2"],
31
+ button_type="success"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  )
33
+
34
+ # Continent Options
35
+ continents = ["World", "Asia", "Oceania", "Europe", "Africa", "North America", "South America", "Atarctica"]
36
+
37
+ # Defining the Pipeline
38
+ co2_pipeline = (
39
+ idf[
40
+ (idf.year <= year_slider) &
41
+ (idf.country.isin(continents))
42
+ ]
43
+ .groupby(["country", "year"])[yaxis_co2].mean()
44
+ .to_frame()
45
+ .reset_index()
46
+ .sort_values(by="year")
47
+ .reset_index(drop=True)
48
  )
49
 
50
+ # Creating the Plot
51
+ co2_plot = co2_pipeline.hvplot(
52
+ x = "year",
53
+ by = "country",
54
+ y=yaxis_co2,
55
+ line_width = 2,
56
+ title = "CO2 emission by continent")
57
+
58
+
59
+ # ------------- Table-CO2 emission over time by continent -----------------
60
+
61
+ # Creating the Table
62
+ co2_table = co2_pipeline.pipe(pn.widgets.Tabulator, pagination="remote", page_size = 10, sizing_mode = "stretch_width")
63
+
64
+ # ------------- CO2 vs GDP scatterplot -----------------------------------
65
+
66
+ # Creating the Pipeline
67
+ co2_vs_gdp_scatterplot_pipeline = (
68
+ idf[
69
+ (idf.year == year_slider) &
70
+ (~ (idf.country.isin(continents)))
71
+ ].groupby(["country", "year", "gdp_per_capita"])["co2"].mean()
72
+ .to_frame().reset_index().sort_values(by="year").reset_index(drop=True)
73
+ )
74
+
75
+ # Creating the Plot
76
+ co2_vs_gdp_scatterplot = co2_vs_gdp_scatterplot_pipeline.hvplot(x="gdp_per_capita",
77
+ y="co2",
78
+ by="country",
79
+ size=80,
80
+ kind="scatter",
81
+ alpha=0.7,
82
+ legend=False,
83
+ height=500,
84
+ width=500)
85
+
86
+ # ------------- Bar chart with CO2 sources by continent ------------------
87
+
88
+ # Y-axis Content
89
+ yaxis_co2_source = pn.widgets.RadioButtonGroup(
90
+ name="Y axis",
91
+ options=["coal_co2", "oil_co2", "gas_co2"],
92
+ button_type="success"
93
  )
94
 
95
+ # Continent Options
96
+ continents_excl_world = ["Asia", "Oceania", "Europe", "Africa", "North America", "South America", "Antarctica"]
97
+
98
+ # Creating the Pipeline
99
+ co2_source_bar_pipeline = (
100
+ idf[
101
+ (idf.year == year_slider) &
102
+ (idf.country.isin(continents_excl_world))
103
+ ].groupby(["year", "country"])[yaxis_co2_source].sum()
104
+ .to_frame()
105
+ .reset_index()
106
+ .sort_values(by="year")
107
+ .reset_index(drop=True)
108
  )
109
 
110
+ # Create the Plot
111
+ co2_source_bar_plot = co2_source_bar_pipeline.hvplot(kind="bar",
112
+ x="country",
113
+ y=yaxis_co2_source,
114
+ title="CO2 source by continent")
115
+
116
+ # ------------------------------ Creating the Dashboard --------------------------------
117
+
118
+ # Layout using Template
119
+ template = pn.template.FastListTemplate(
120
+ title='World CO2 emission dashboard',
121
+ sidebar=[pn.pane.Markdown("# CO2 Emissions and Climate Change"),
122
+ pn.pane.Markdown("#### Carbon dioxide emissions are the primary driver of global climate change. It’s widely recognised that to avoid the worst impacts of climate change, the world needs to urgently reduce emissions. But, how this responsibility is shared between regions, countries, and individuals has been an endless point of contention in international discussions."),
123
+ pn.pane.PNG('climate_day.png', sizing_mode='scale_both'),
124
+ pn.pane.Markdown("## Settings"),
125
+ year_slider],
126
+ main=[pn.Row(pn.Column(yaxis_co2,
127
+ co2_plot.panel(width=700), margin=(0,25)),
128
+ co2_table.panel(width=500)),
129
+ pn.Row(pn.Column(co2_vs_gdp_scatterplot.panel(width=600), margin=(0,25)),
130
+ pn.Column(yaxis_co2_source, co2_source_bar_plot.panel(width=600)))],
131
+ accent_base_color="#88d8b0",
132
+ header_background="#88d8b0",
133
  )
134
 
135
+ # ----------------- Run the Dashboard ------------------------
136
+
137
+ if __name__ == "__main__":
138
+ template.show()