Spaces:
Runtime error
Runtime error
Commit ·
9e9fffd
1
Parent(s): 0d60d8d
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,147 +1,175 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
from typing import List, Tuple
|
| 4 |
|
| 5 |
-
|
| 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 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
class_names,
|
| 118 |
-
)
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
)
|
| 125 |
|
| 126 |
-
#
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Comparable_Win_Calculator.ipynb
|
|
|
|
| 3 |
|
| 4 |
+
Automatically generated by Colaboratory.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/12e5diH3JZC7rGY28DWuH6ysWHuyfEwNx
|
| 8 |
+
"""
|
|
|
|
|
|
|
| 9 |
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import numpy as np
|
| 12 |
+
import panel as pn
|
| 13 |
+
from pyecharts.charts.basic_charts.bar import Bar
|
| 14 |
+
from pyecharts import options as opts
|
| 15 |
+
import hvplot.pandas
|
| 16 |
+
import math
|
| 17 |
+
pn.extension('mathjax')
|
| 18 |
+
pn.extension('tabulator')
|
| 19 |
+
pn.extension('echarts')
|
| 20 |
+
|
| 21 |
+
df_1 = pd.read_csv("primary.csv")
|
| 22 |
+
df_2 = pd.read_csv("general.csv")
|
| 23 |
+
|
| 24 |
+
# make dataframe pipline interactive
|
| 25 |
+
idf_1 = df_1.interactive()
|
| 26 |
+
idf_2 = df_2.interactive()
|
| 27 |
+
|
| 28 |
+
# Using primary
|
| 29 |
+
HD_list = [i for i in range(1,41)]
|
| 30 |
+
|
| 31 |
+
"""# Create Table1"""
|
| 32 |
+
|
| 33 |
+
def first_table(HD_selector,turnout_level):
|
| 34 |
+
pri_conser = df_1.loc[(df_1['HD'] == str(HD_selector)) & (df_1['Primary Voting'] == turnout_level)].Conservatives
|
| 35 |
+
pri_right = df_1.loc[(df_1['HD'] == str(HD_selector)) & (df_1['Primary Voting'] == turnout_level)].Right_Leaning
|
| 36 |
+
pri_left = df_1.loc[(df_1['HD'] == str(HD_selector)) & (df_1['Primary Voting'] == turnout_level)].Left_Leaning
|
| 37 |
+
pri_liberal = df_1.loc[(df_1['HD'] == str(HD_selector)) & (df_1['Primary Voting'] == turnout_level)].Liberals
|
| 38 |
+
|
| 39 |
+
gen_conser = df_2.loc[(df_2['HD'] == str(HD_selector)) & (df_2['General Voting'] == turnout_level)].Conservatives
|
| 40 |
+
gen_right = df_2.loc[(df_2['HD'] == str(HD_selector)) & (df_2['General Voting'] == turnout_level)].Right_Leaning
|
| 41 |
+
gen_left = df_2.loc[(df_2['HD'] == str(HD_selector)) & (df_2['General Voting'] == turnout_level)].Left_Leaning
|
| 42 |
+
gen_liberal = df_2.loc[(df_2['HD'] == str(HD_selector)) & (df_2['General Voting'] == turnout_level)].Liberals
|
| 43 |
+
|
| 44 |
+
table1_df = pd.DataFrame({
|
| 45 |
+
'Primary': [pri_conser, pri_right,pri_left,pri_liberal],
|
| 46 |
+
'Global': [gen_conser, gen_right,gen_left,gen_liberal],
|
| 47 |
+
}, index=['0-20 (Conservatives)','20-40 (Right Leaning Moderates)','40-70 (Left Leaning Moderates)','70-100 (Liberals)'])
|
| 48 |
+
df_widget = pn.widgets.Tabulator(table1_df,widths=130,theme_classes=['thead-dark', 'table-sm'])
|
| 49 |
+
return df_widget
|
| 50 |
+
|
| 51 |
+
"""# Plot Graph1"""
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# Plot dashboard_1
|
| 55 |
+
def dash_board_1(HD_selector_1,turnout_level_1,HD_selector_2,turnout_level_2,index):
|
| 56 |
+
pri_conser_1 = df_1.loc[(df_1['HD'] == str(HD_selector_1)) & (df_1['Primary Voting'] == turnout_level_1)].Conservatives
|
| 57 |
+
#print(type(pri_conser_1))
|
| 58 |
+
# print(type(pri_conser_1.item()))
|
| 59 |
+
pri_right_1 = (df_1.loc[(df_1['HD'] == str(HD_selector_1)) & (df_1['Primary Voting'] == turnout_level_1)].Right_Leaning)
|
| 60 |
+
# print(type(pri_right_1))
|
| 61 |
+
# print(type(pri_right_1.item()))
|
| 62 |
+
pri_left_1 = df_1.loc[(df_1['HD'] == str(HD_selector_1)) & (df_1['Primary Voting'] == turnout_level_1)].Left_Leaning
|
| 63 |
+
pri_liberal_1 = df_1.loc[(df_1['HD'] == str(HD_selector_1)) & (df_1['Primary Voting'] == turnout_level_1)].Liberals
|
| 64 |
+
total_1 = pri_conser_1 + pri_right_1 + pri_left_1+ pri_liberal_1
|
| 65 |
+
conser_percen_1 = round(100*pri_conser_1/total_1,2)
|
| 66 |
+
right_percen_1 = round(100*pri_right_1/total_1,2)
|
| 67 |
+
left_percen_1 = round(100*pri_left_1/total_1,2)
|
| 68 |
+
liberal_percen_1 = round(100*pri_liberal_1/total_1,2)
|
| 69 |
+
pri_conser_2 = (df_1.loc[(df_1['HD'] == str(HD_selector_2)) & (df_1['Primary Voting'] == turnout_level_2)].Conservatives)
|
| 70 |
+
pri_right_2 = (df_1.loc[(df_1['HD'] == str(HD_selector_2)) & (df_1['Primary Voting'] == turnout_level_2)].Right_Leaning)
|
| 71 |
+
pri_left_2 = (df_1.loc[(df_1['HD'] == str(HD_selector_2)) & (df_1['Primary Voting'] == turnout_level_2)].Left_Leaning)
|
| 72 |
+
pri_liberal_2 = (df_1.loc[(df_1['HD'] == str(HD_selector_2)) & (df_1['Primary Voting'] == turnout_level_2)].Liberals)
|
| 73 |
+
total_2 = pri_conser_2 + pri_right_2 + pri_left_2 + pri_liberal_2
|
| 74 |
+
conser_percen_2 = round(100*pri_conser_2/total_2,2)
|
| 75 |
+
right_percen_2 = round(100*pri_right_2/total_2,2)
|
| 76 |
+
left_percen_2 = round(100*pri_left_2/total_2,2)
|
| 77 |
+
liberal_percen_2 = round(100*pri_liberal_2/total_2,2)
|
| 78 |
+
center= ['50%','60%'], # Percentage of graph's distance to the left and top
|
| 79 |
+
#print([conser_percen_1,right_percen_1,left_percen_1,liberal_percen_1])
|
| 80 |
+
#print([pri_conser_1.item(), pri_right_1.item(),pri_left_1.item(),pri_liberal_1.item()])
|
| 81 |
+
bar_1= (Bar()
|
| 82 |
+
.add_xaxis(["(0-20)Conservative","(20-40)Right Leaning Moderates","(40-70)left Leaning Moderates","70-100 (Liberals)"])
|
| 83 |
+
.add_yaxis("HD"+str(HD_selector_1), [conser_percen_1.item(),right_percen_1.item(),left_percen_1.item(),liberal_percen_1.item()])
|
| 84 |
+
.add_yaxis("HD"+str(HD_selector_2), [conser_percen_2.item(),right_percen_2.item(),left_percen_2.item(),liberal_percen_2.item()])
|
| 85 |
+
.set_global_opts(title_opts=opts.TitleOpts(title="General Election District Comparison (%)",
|
| 86 |
+
pos_left="center", pos_top="top"),
|
| 87 |
+
legend_opts = opts.LegendOpts(type_="scroll", pos_left="70%", orient='vertical', pos_top="10%"),
|
| 88 |
+
)
|
| 89 |
+
)
|
| 90 |
+
bar_2= (Bar()
|
| 91 |
+
.add_xaxis(["(0-20)Conservative","(20-40)Right Leaning Moderates","(40-70)left Leaning Moderates","70-100 (Liberals)"])
|
| 92 |
+
.add_yaxis("HD"+str(HD_selector_1), [pri_conser_1.item(), pri_right_1.item(),pri_left_1.item(),pri_liberal_1.item()])
|
| 93 |
+
.add_yaxis("HD"+str(HD_selector_2), [pri_conser_2.item(),pri_right_2.item(),pri_left_2.item(),pri_liberal_2.item()])
|
| 94 |
+
.set_global_opts(title_opts=opts.TitleOpts(title="General Election District Comparison (Raw Numbers)",
|
| 95 |
+
pos_left="center", pos_top="top"),
|
| 96 |
+
legend_opts = opts.LegendOpts(type_="scroll", pos_left="70%", orient='vertical', pos_top="10%"),
|
| 97 |
+
)
|
| 98 |
+
)
|
| 99 |
+
bar_1 = pn.pane.ECharts(bar_1, width=1000, height=500)
|
| 100 |
+
bar_2 = pn.pane.ECharts(bar_2, width=1000, height=500)
|
| 101 |
+
bar_list = [bar_1,bar_2]
|
| 102 |
+
return bar_list[index]
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
"""# Declare SideBar Elements"""
|
| 106 |
+
|
| 107 |
+
# House District Selector Widget 1
|
| 108 |
+
HD_selector_1 = pn.widgets.Select(name='HD Selector', options=HD_list)
|
| 109 |
+
# turnout_level selection 1
|
| 110 |
+
turnout_level_1 = pn.widgets.Select(name='Turnout Level', options=['High Prop', 'Low Prop'])
|
| 111 |
+
|
| 112 |
+
# House District Selector Widget 2
|
| 113 |
+
HD_selector_2 = pn.widgets.Select(name='HD Selector', options=HD_list)
|
| 114 |
+
# turnout_level selection 2
|
| 115 |
+
turnout_level_2 = pn.widgets.Select(name='Turnout Level', options=['High Prop', 'Low Prop'])
|
| 116 |
+
|
| 117 |
+
title = """
|
| 118 |
+
# Comparable Win Calculator
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
explaination_1 = """
|
| 122 |
+
### Enter a house distirct and specify the turnout level.
|
| 123 |
+
### The tables below will show the ideological composition of the low/high propensity electorate in your district in both the primary and the general.
|
| 124 |
+
### Underneath you will see a graph conveying the same information in terms of percentages.
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
widget_name_1 = """
|
| 128 |
+
### Choose first House District
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
widget_name_2 = """
|
| 132 |
+
### High prop or Low prop
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
widget_name_3 = """
|
| 136 |
+
### Choose second House District
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
widget_name_4 = """
|
| 140 |
+
### High prop or Low prop
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
sidebar = pn.layout.WidgetBox(
|
| 144 |
+
pn.pane.Markdown(title, margin=(0, 10)),
|
| 145 |
+
pn.pane.Markdown(widget_name_1, margin=(0, 10)),
|
| 146 |
+
HD_selector_1,
|
| 147 |
+
pn.pane.Markdown(widget_name_2, margin=(0, 10)),
|
| 148 |
+
turnout_level_1,
|
| 149 |
+
pn.pane.Markdown(widget_name_3, margin=(0, 10)),
|
| 150 |
+
HD_selector_2,
|
| 151 |
+
pn.pane.Markdown(widget_name_4, margin=(0, 10)),
|
| 152 |
+
turnout_level_2,
|
| 153 |
+
max_width=350,
|
| 154 |
+
sizing_mode='stretch_width'
|
| 155 |
)
|
| 156 |
|
| 157 |
+
"""# Main Panel"""
|
| 158 |
+
|
| 159 |
+
main = pn.Row(
|
| 160 |
+
pn.Column(
|
| 161 |
+
pn.pane.Markdown(explaination_1, margin=(0, 40)),
|
| 162 |
+
pn.layout.Divider(margin=(-10, 0, 0, 0),),
|
| 163 |
+
pn.Row(
|
| 164 |
+
pn.bind(first_table,HD_selector_1,turnout_level_1),
|
| 165 |
+
pn.bind(first_table,HD_selector_2,turnout_level_2),
|
| 166 |
+
),
|
| 167 |
+
pn.Row(
|
| 168 |
+
pn.bind(dash_board_1,HD_selector_1,turnout_level_1,HD_selector_2,turnout_level_2,0),
|
| 169 |
+
pn.bind(dash_board_1,HD_selector_1,turnout_level_1,HD_selector_2,turnout_level_2,1),
|
| 170 |
+
),
|
| 171 |
+
),
|
| 172 |
+
|
| 173 |
)
|
| 174 |
+
overall = pn.Row(sidebar, main).servable()
|
| 175 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|