{"cells":[{"metadata":{},"cell_type":"markdown","source":"### A noob's attempt inspired by [this kernel](https://www.kaggle.com/iafoss/grapheme-fast-ai-starter-inference) from @lafoss"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2\nimport zipfile\nfrom tqdm import tqdm_notebook as tqdm\nimport random\nimport torch\nimport torchvision\n\nSEED = 42\nLABELS = 'train.csv'\n\nimport fastai\nfrom fastai.vision import *\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nfastai.__version__","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"HEIGHT = 137\nWIDTH = 236\nSIZE = (128,128)\nBATCH = 64\n\nPATH = '/kaggle/input/bengaliai-cv19/'\n\nTEST = [PATH+'test_image_data_0.parquet',\n        PATH+'test_image_data_1.parquet',\n        PATH+'test_image_data_2.parquet',\n        PATH+'test_image_data_3.parquet']\n\nTRAIN = [PATH+'train_image_data_0.parquet',\n         PATH+'train_image_data_1.parquet',\n         PATH+'train_image_data_2.parquet',\n         PATH+'train_image_data_3.parquet']\n\ndf_test = pd.read_csv(PATH+'test.csv')\ndf_test.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#!mkdir '/kaggle/working/test'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def bbox(img):\n    rows = np.any(img, axis=1)\n    cols = np.any(img, axis=0)\n    rmin, rmax = np.where(rows)[0][[0, -1]]\n    cmin, cmax = np.where(cols)[0][[0, -1]]\n    return rmin, rmax, cmin, cmax\n\ndef crop_resize(img0, size=SIZE, pad=16):\n    #crop a box around pixels large than the threshold \n    #some images contain line at the sides\n    ymin,ymax,xmin,xmax = bbox(img0[5:-5,5:-5] > 80)\n    #cropping may cut too much, so we need to add it back\n    xmin = xmin - 13 if (xmin > 13) else 0\n    ymin = ymin - 10 if (ymin > 10) else 0\n    xmax = xmax + 13 if (xmax < WIDTH - 13) else WIDTH\n    ymax = ymax + 10 if (ymax < HEIGHT - 10) else HEIGHT\n    img = img0[ymin:ymax,xmin:xmax]\n    #remove lo intensity pixels as noise\n    img[img < 28] = 0\n    lx, ly = xmax-xmin,ymax-ymin\n    l = max(lx,ly) + pad\n    #make sure that the aspect ratio is kept in rescaling\n    img = np.pad(img, [((l-ly)//2,), ((l-lx)//2,)], mode='constant')\n    return cv2.resize(img,size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn = load_learner(Path('/kaggle/input/bgraph-rn50-model'),'try2A-rn50-im128-wcv.pkl')\n#preds, _ = learn.get_preds(ds_type=DatasetType.Test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# def fillLabels(label,prob,th):\n#     thresh, label = th, str(label)\n#     print(label)\n#     if ('c_' in label) & ('r_' in label) & ('v_' in label):\n#         for s in ['c_','r_','v_']:\n#             fo = label.index(s) + len(s)+1\n#             label = label[:fo]+label[fo:]\n#     elif 'c_' not in label:\n#         p = prob[:7].numpy()\n#         while all(p<thresh):\n#             thresh -= 0.01\n#         idx = np.argwhere(p>thresh)[0][0]\n#         label = 'c_'+str(idx)+';'+label\n#     elif 'r_' not in label:\n#         p = prob[7:175].numpy()\n#         while all(p<thresh):\n#             thresh -= 0.01\n#         idx = np.argwhere(p>thresh)[0][0]\n#         label = label.split(';')[0]+';'+'r_'+str(idx)+';'+label.split(';')[1]\n#     elif 'v_' not in label:\n#         p = prob[175:].numpy()\n#         while all(p<thresh):\n#             thresh -= 0.01\n#         idx = np.argwhere(p>thresh)[0][0]\n#         label = label+';'+'v_'+str(idx)\n#     label = [s.split('_')[1] for s in label.split(';')]\n#     return label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nrow_id,target = [],[]\nimgnet_mean = [0.485, 0.456, 0.406] # Here it's ImageNet statistics\nimgnet_std = [0.229, 0.224, 0.225]\n\n\nfor fname in TEST:\n    df = pd.read_parquet(fname)\n    data = 255 - df.iloc[:, 1:].values.reshape(-1, HEIGHT, WIDTH).astype(np.uint8)\n    for idx in range(len(df)):\n        name = df.iloc[idx,0]\n        img = (data[idx]*(255.0/data[idx].max())).astype(np.uint8)\n        img = crop_resize(img)\n        img = np.stack((img,)*3,axis=-1)\n        img = pil2tensor(img,np.float32).div_(255)\n        pred, tsor, prob = learn.predict(Image(img))\n        row_id += [f'{name}_consonant_diacritic',f'{name}_grapheme_root',f'{name}_vowel_diacritic']\n        #labels = fillLabels(pred,prob,0.9)\n        c = learn.data.classes\n        #t = [c[i] for i in torch.topk(prob,3)[1].numpy()]\n        target += [\n                c[ np.argmax(prob[:7].numpy()) ].split('_')[1],\n                c[ np.argmax(prob[7:175].numpy()) + 7 ].split('_')[1],\n                c[ np.argmax(prob[175:].numpy()) + 175 ].split('_')[1] ]\n\n\nsub_df = pd.DataFrame({'row_id': row_id, 'target': target})\nsub_df.to_csv('submission.csv', index=False)\nsub_df","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":1}