def open_im_by_folder(FOLDER, sufx=suffixes): """ FOLDER : Folder containing sample files sufx : color suffixes for samples """ FOLDER = Path(FOLDER) fnames = sorted(FOLDER.ls()) fnames = [fnames[2], fnames[1], fnames[0], fnames[3]] # Sorting according to RGBY from BGRY imgs = [cv2.imread(str(o), cv2.IMREAD_GRAYSCALE) for o in fnames] # List of 4 channels of given file ID imgs = np.stack(imgs, 2) return Image(pil2tensor( imgs, np.float32).float()) # Creating a Fastai Image object from the image
def get_folder(): is_repeating = False is_folder_valid = False while not is_folder_valid: prompt = "Enter the location of the folder containing the samples : " if not is_repeating \ else "Please enter a valid folder : " try: folder = Path(input(prompt)) if not folder.is_dir(): raise FileNotFoundError else: is_folder_valid = True except FileNotFoundError: is_repeating = True is_folder_valid = False return folder
def classify(filename, learn): file = Path(UPLOAD_FOLDER) / filename image = open_image(file) pred = learn.predict(image) return pred[0]
def get_folder_by_ID(ROOT=ROOT): is_repeating = False is_ID_valid = False while not is_ID_valid: prompt = "Enter the ID of the samples : " if not is_repeating \ else "Please enter a valid ID : " try: ID = Path(input(prompt)) folder = ROOT / ID if not folder.is_dir(): raise FileNotFoundError else: is_ID_valid = True except FileNotFoundError: is_repeating = True is_ID_valid = False return folder
from starlette.applications import Starlette from starlette.responses import HTMLResponse, JSONResponse from starlette.staticfiles import StaticFiles from starlette.middleware.cors import CORSMiddleware import uvicorn, aiohttp, asyncio from io import BytesIO from fastai.vision import ImageDataBunch, create_cnn, open_image, get_transforms, imagenet_stats, models from fastai import Path model_file_url = 'https://www.dropbox.com/s/y4kl2gv1akv7y4i/stage-2.pth?raw=1' model_file_name = 'model' classes = ['black', 'grizzly', 'teddys'] path = Path(__file__).parent app = Starlette() app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_headers=['X-Requested-With', 'Content-Type']) app.mount('/static', StaticFiles(directory='app/static')) async def download_file(url, dest): if dest.exists(): return async with aiohttp.ClientSession() as session: async with session.get(url) as response: data = await response.read() with open(dest, 'wb') as f: f.write(data)
from fastai import Path import cv2 import numpy as np from fastai.vision import Image, pil2tensor import matplotlib.pyplot as plt ROOT = Path('data/demonstration') suffixes = ['_red.png', '_green.png', '_blue.png', '_yellow.png'] prompt = "Do you want to make predictions based on a folder or ID (1 or 2) ? " def open_im_by_id(ID, ROOT=ROOT, sufx=suffixes): """ ID : Base name for each sample ROOT : Folder containing all samples sufx : color suffixes for samples """ imnames = [ROOT / ID / (ID + o) for o in sufx] # Generating file names for given image ID imgs = [cv2.imread(str(o), cv2.IMREAD_GRAYSCALE) for o in imnames] # List of 4 channels of given file ID imgs = np.stack(imgs, 2) return Image(pil2tensor( imgs, np.float32).float()) # Creating a Fastai Image object from the image def open_im_by_folder(FOLDER, sufx=suffixes): """ FOLDER : Folder containing sample files sufx : color suffixes for samples
def load_classes(file, path=Path('.')): path = path / 'models' file = path / file filestr = str(file) with open(filestr + '.classes', 'r') as f: return json.loads(f.read())
def save_classes(file, classes, path=Path('.')): path = path / 'models' file = path / file filestr = str(file) with open(filestr + '.classes', 'w') as f: f.write(json.dumps(classes))
from fastai import Path from fastai import Config import json #path = Path(Config.get_key('data_path')).expanduser()/'handwritten' # /mnt/handwritten is a path specific to azure datascience machine. If it does not work, uncomment the line above # and comment line below ramdisk_path = Path('/tmp/ramdisk') path = Path(ramdisk_path / 'handwritten') permanent_path = Path(Config.get_key('data_path')).expanduser() / 'handwritten' def save_classes(file, classes, path=Path('.')): path = path / 'models' file = path / file filestr = str(file) with open(filestr + '.classes', 'w') as f: f.write(json.dumps(classes)) def load_classes(file, path=Path('.')): path = path / 'models' file = path / file filestr = str(file) with open(filestr + '.classes', 'r') as f: return json.loads(f.read())
def create_network(): empty_data = ImageDataBunch.load_empty(Path(UPLOAD_FOLDER), 'export.pkl') learn = create_cnn(empty_data, models.resnet18).load('stage-2') return learn