Update app.py
Browse files
app.py
CHANGED
@@ -1,147 +1,64 @@
|
|
1 |
-
import io
|
2 |
-
import random
|
3 |
-
from typing import List, Tuple
|
4 |
-
|
5 |
-
import aiohttp
|
6 |
import panel as pn
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
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 |
-
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 |
-
|
40 |
-
async with session.get(image_url) as resp:
|
41 |
-
return Image.open(io.BytesIO(await resp.read()))
|
42 |
|
|
|
|
|
43 |
|
44 |
-
def
|
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 |
-
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 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
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 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
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 |
-
|
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 pandas as pd
|
3 |
+
import os
|
4 |
+
import datetime
|
5 |
+
import io
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
+
from google_sheet import fetch_leaderboard
|
8 |
+
from google_drive import upload_to_drive
|
9 |
|
10 |
+
pn.extension()
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
+
# File upload widget
|
13 |
+
file_input = pn.widgets.FileInput(accept='.zip', multiple=False)
|
14 |
|
15 |
+
# Status message
|
16 |
+
status = pn.pane.Markdown("")
|
|
|
|
|
17 |
|
18 |
+
# Leaderboard display
|
19 |
+
leaderboard = pn.pane.DataFrame(pd.DataFrame(), width=600)
|
20 |
|
21 |
+
def submit_file(event):
|
22 |
+
if file_input.value is None:
|
23 |
+
status.object = "⚠️ Please upload a .zip file before submitting."
|
24 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
+
# Save uploaded file
|
27 |
+
timestamp = datetime.datetime.now().isoformat().replace(":", "_")
|
28 |
+
filename = f"{timestamp}_{file_input.filename}"
|
29 |
+
submission_path = os.path.join("submissions", filename)
|
30 |
+
os.makedirs("submissions", exist_ok=True)
|
31 |
+
with open(submission_path, "wb") as f:
|
32 |
+
f.write(file_input.value)
|
33 |
|
|
|
|
|
|
|
|
|
|
|
34 |
try:
|
35 |
+
drive_file_id = upload_to_drive(submission_path, filename)
|
36 |
+
status.object = f"✅ Uploaded to Google Drive [File ID: {drive_file_id}]"
|
37 |
+
except Exception as e:
|
38 |
+
status.object = f"❌ Failed to upload to Google Drive: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
+
# Update leaderboard
|
41 |
+
try:
|
42 |
+
df = fetch_leaderboard()
|
43 |
+
if not df.empty:
|
44 |
+
df_sorted = df.sort_values(by="score", ascending=False)
|
45 |
+
leaderboard.object = df_sorted
|
46 |
+
else:
|
47 |
+
leaderboard.object = pd.DataFrame()
|
48 |
+
except Exception as e:
|
49 |
+
status.object += f"\n⚠️ Could not load leaderboard: {e}"
|
50 |
+
|
51 |
+
submit_button = pn.widgets.Button(name="Submit", button_type="primary")
|
52 |
+
submit_button.on_click(submit_file)
|
53 |
+
|
54 |
+
# Layout
|
55 |
+
app = pn.Column(
|
56 |
+
"## 🏆 Hackathon Leaderboard",
|
57 |
+
file_input,
|
58 |
+
submit_button,
|
59 |
+
status,
|
60 |
+
"### Leaderboard",
|
61 |
+
leaderboard
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
)
|
63 |
|
64 |
+
app.servable()
|
|
|
|
|
|
|
|
|
|
|
|