{ "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": [ "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/html": [ "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "\n", "
\n", " \n", " 0.00% [0/1 00:00<?]\n", "
\n", " " ], "text/plain": [ "" ] }, "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 }