Spaces:
Build error
Build error
File size: 13,603 Bytes
118e0d5 cb6f6ef 118e0d5 cb6f6ef 118e0d5 cb6f6ef 118e0d5 cb6f6ef 118e0d5 cb6f6ef 118e0d5 cb6f6ef 118e0d5 cb6f6ef 118e0d5 cb6f6ef 118e0d5 cb6f6ef 118e0d5 cb6f6ef 118e0d5 cb6f6ef 118e0d5 cb6f6ef 118e0d5 cb6f6ef 118e0d5 cb6f6ef 118e0d5 cb6f6ef 118e0d5 cb6f6ef 118e0d5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import timm\n",
"from fastai.vision.all import *\n",
"import gradio as gr\n",
"import os\n",
"\n",
"\n",
"import platform\n",
"if platform.system() == 'Windows':\n",
" import pathlib\n",
" temp = pathlib.PosixPath\n",
" pathlib.PosixPath = pathlib.WindowsPath"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"themes = sorted(('City', 'Technic', 'Star-Wars', 'Creator', 'Ninjago', 'Architecture', 'Duplo', 'Friends', 'DC-Comics-Super-Heroes'))\n",
"learn_color = load_learner('models/lego_convnext_small_4ep_sets05-19.pkl')\n",
"learn_gray = load_learner('models/lego_convnext_small_4ep_grayscale.pkl')\n",
"\n",
"def classify(img, *args):\n",
" if args[-1] == 'Color mode':\n",
" _, _, probs = learn_color.predict(img)\n",
" else:\n",
" _, _, probs = learn_gray.predict(img)\n",
" return dict(zip(themes, map(float, probs)))\n",
"\n",
"\n",
"img = gr.components.Image(shape=(192, 192), label=\"Input image\")\n",
"is_color = gr.components.Radio(['Color mode', 'Grayscale mode'], value='Color mode', show_label=False)\n",
"real_label = gr.components.Textbox(\"\", label='Theme', interactive=False)\n",
"year = gr.components.Textbox(\"\", label='Release year', visible=False)\n",
"\n",
"label = gr.components.Label(label='Predictions')\n",
"examples = [[f'test_images/{img_name}', img_name.split('2', 1)[0].capitalize(), img_name.split('.', 1)[0][-4:]] for img_name in os.listdir('test_images')]\n",
"\n",
"# gr.Interface(fn=classify, inputs=[img, real_label, year, is_color], outputs=label, examples=examples).launch(\n",
"# # inline=False\n",
"# )"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"title = 'LEGO sets&creations theme classifier'\n",
"description = f'''\n",
"# {title}\n",
"This demo showcases the LEGO theme classifier built with the help of fast.ai. A model was trained using over 1800 images of sets released in 2005-19 scraped from the Brickset LEGO database.\n",
"To test how much overfitting might be present due to the model memorizing the color(s) associated with a particular theme, I ran the training again using the same set of images, but in grayscale. Hence two available models.\n",
"\n",
"I was especially intrested in how the model will do on MOCS a.k.a. community creations, since the boundries between themes are not well-defined. Enjoy!\n",
"'''"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\gradio\\deprecation.py:43: UserWarning: You have unused kwarg parameters in Row, please remove them: {'equal_height': True}\n",
" warnings.warn(\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Running on local URL: http://127.0.0.1:7860\n",
"\n",
"To create a public link, set `share=True` in `launch()`.\n"
]
},
{
"data": {
"text/html": [
"<div><iframe src=\"http://127.0.0.1:7860/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": []
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"text/html": [
"\n",
"<style>\n",
" /* Turns off some styling */\n",
" progress {\n",
" /* gets rid of default border in Firefox and Opera. */\n",
" border: none;\n",
" /* Needs to be in here for Safari polyfill so background images work as expected. */\n",
" background-size: auto;\n",
" }\n",
" progress:not([value]), progress:not([value])::-webkit-progress-bar {\n",
" background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);\n",
" }\n",
" .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {\n",
" background: #F44336;\n",
" }\n",
"</style>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"\n",
" <div>\n",
" <progress value='0' class='' max='1' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
" 0.00% [0/1 00:00<?]\n",
" </div>\n",
" "
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"Traceback (most recent call last):\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\gradio\\routes.py\", line 321, in run_predict\n",
" output = await app.blocks.process_api(\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\gradio\\blocks.py\", line 1015, in process_api\n",
" result = await self.call_function(fn_index, inputs, iterator, request)\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\gradio\\blocks.py\", line 856, in call_function\n",
" prediction = await anyio.to_thread.run_sync(\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\anyio\\to_thread.py\", line 31, in run_sync\n",
" return await get_asynclib().run_sync_in_worker_thread(\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\anyio\\_backends\\_asyncio.py\", line 937, in run_sync_in_worker_thread\n",
" return await future\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\anyio\\_backends\\_asyncio.py\", line 867, in run\n",
" result = context.run(func, *args)\n",
" File \"C:\\Users\\ewafa\\AppData\\Local\\Temp\\ipykernel_20024\\986269756.py\", line 9, in classify\n",
" _, _, probs = learn_color.predict(img)\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\fastai\\learner.py\", line 313, in predict\n",
" inp,preds,_,dec_preds = self.get_preds(dl=dl, with_input=True, with_decoded=True)\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\fastai\\learner.py\", line 300, in get_preds\n",
" self._do_epoch_validate(dl=dl)\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\fastai\\learner.py\", line 236, in _do_epoch_validate\n",
" with torch.no_grad(): self._with_events(self.all_batches, 'validate', CancelValidException)\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\fastai\\learner.py\", line 193, in _with_events\n",
" try: self(f'before_{event_type}'); f()\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\fastai\\learner.py\", line 199, in all_batches\n",
" for o in enumerate(self.dl): self.one_batch(*o)\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\fastai\\learner.py\", line 227, in one_batch\n",
" self._with_events(self._do_one_batch, 'batch', CancelBatchException)\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\fastai\\learner.py\", line 193, in _with_events\n",
" try: self(f'before_{event_type}'); f()\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\fastai\\learner.py\", line 205, in _do_one_batch\n",
" self.pred = self.model(*self.xb)\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\torch\\nn\\modules\\module.py\", line 1194, in _call_impl\n",
" return forward_call(*input, **kwargs)\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\torch\\nn\\modules\\container.py\", line 204, in forward\n",
" input = module(input)\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\torch\\nn\\modules\\module.py\", line 1194, in _call_impl\n",
" return forward_call(*input, **kwargs)\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\fastai\\vision\\learner.py\", line 177, in forward\n",
" def forward(self,x): return self.model.forward_features(x) if self.needs_pool else self.model(x)\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\timm\\models\\convnext.py\", line 397, in forward_features\n",
" x = self.stem(x)\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\torch\\nn\\modules\\module.py\", line 1194, in _call_impl\n",
" return forward_call(*input, **kwargs)\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\torch\\nn\\modules\\container.py\", line 204, in forward\n",
" input = module(input)\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\torch\\nn\\modules\\module.py\", line 1194, in _call_impl\n",
" return forward_call(*input, **kwargs)\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\timm\\models\\layers\\norm.py\", line 67, in forward\n",
" if self._fast_norm:\n",
" File \"c:\\Users\\ewafa\\anaconda3\\envs\\ml\\lib\\site-packages\\torch\\nn\\modules\\module.py\", line 1269, in __getattr__\n",
" raise AttributeError(\"'{}' object has no attribute '{}'\".format(\n",
"AttributeError: 'LayerNorm2d' object has no attribute '_fast_norm'\n"
]
}
],
"source": [
"themes = sorted(('City', 'Technic', 'Star-Wars', 'Creator', 'Ninjago', 'Architecture', 'Duplo', 'Friends', 'DC-Comics-Super-Heroes'))\n",
"learn_color = load_learner('models/lego_convnext_small_4ep_sets05-19.pkl')\n",
"learn_gray = load_learner('models/lego_convnext_small_4ep_grayscale.pkl')\n",
"\n",
"def classify(img, is_color):\n",
" if is_color == 'Grayscale model':\n",
" _, _, probs = learn_gray.predict(img)\n",
" else:\n",
" _, _, probs = learn_color.predict(img)\n",
" return dict(zip(themes, map(float, probs)))\n",
"\n",
"\n",
"examples_sets = [[f'images/sets/{img_name}', img_name.split('2', 1)[0].capitalize(), img_name.split('.', 1)[0][-4:]] for img_name in os.listdir('images/sets')]\n",
"examples_mocs = [['images/mocs/modernlibrary.jpg', 'Modern library MOC'],\n",
" ['images/mocs/keanu.jpg', 'Keanu Reeves himself'],\n",
" ['images/mocs/solaris.jfif', 'Solaris Urbino articulated bus'],\n",
" ['images/mocs/aroundtheworld.jpg', '\"Around the World\" MOC'],\n",
" ['images/mocs/walkingminicooper.jpg', 'Walking mini cooper. Yes, walking mini cooper']]\n",
"\n",
"with gr.Blocks() as app:\n",
" gr.Markdown(description)\n",
" with gr.Row(equal_height=True):\n",
" with gr.Column():\n",
" img = gr.components.Image(shape=(192, 192), label=\"Input image\")\n",
" is_color = gr.components.Radio(['Color model', 'Grayscale model'], value='Color model', show_label=False)\n",
" real_label = gr.components.Textbox(\"\", label='Real theme', interactive=False)\n",
" run_btn = gr.Button(\"Predict!\")\n",
" # placeholders for additional info\n",
" name = gr.components.Textbox(\"\", label='Name', visible=False)\n",
" year = gr.components.Textbox(\"\", label='Release year', visible=False)\n",
" with gr.Column():\n",
" prediction = gr.components.Label(label='Prediction')\n",
" with gr.Row():\n",
" with gr.Column():\n",
" ex_sets = gr.Examples(examples_sets, inputs=[img, real_label, year], outputs=prediction, label='Examples - official sets')\n",
" with gr.Column():\n",
" ex_mocs = gr.Examples(examples_mocs, inputs=[img, name], outputs=prediction, label='Examples - community creations')\n",
"\n",
" run_btn.click(fn=classify, inputs=[img, is_color], outputs=prediction)\n",
"\n",
"app.launch()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "ml",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.8 | packaged by conda-forge | (main, Nov 24 2022, 14:07:00) [MSC v.1916 64 bit (AMD64)]"
},
"orig_nbformat": 4,
"vscode": {
"interpreter": {
"hash": "661d60981a8180246504a9562268f79cf2915497a26a99308f4a10e22604b72f"
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|