def upload_file(): if request.method == 'GET': return render_template('upload_file.html') if request.method == 'POST': if "file" not in request.files: print("File not uploaded.") return file = request.files['file'] image = file.read() tensor = get_tensor(image_bytes=image) category, flower = get_flower_name(image_bytes=image) print(get_tensor(image_bytes=image)) return render_template('result_file.html', flower=flower)
def hello_world(): if request.method == 'GET': return render_template('index.html', value='hi') if request.method == 'POST': print(request.files) if 'file' not in request.files: print('file not uploaded') return file = request.files['file'] image = file.read() category, flower_name = get_flower_name(image_bytes=image) get_flower_name(image_bytes=image) tensor = get_tensor(image_bytes=image) print(get_tensor(image_bytes=image)) return render_template('result.html', flower=flower_name, category=category)
def Pnuemonia_detect(): if request.method == 'GET': return render_template('index.html', value='hi') if request.method == 'POST': print(request.files) if 'file' not in request.files: print('file not uploaded') return file = request.files['file'] #image = cv2.imread(file).astype('uint8') image = file.read() #image =np.asarray(file) model = get_model() image = get_tensor(image) output = model.predict(image) if (output == [[0.]]): name = "PNUEMONIA NEGATIVE" else: name = "PNUEMONIA POSITIVE" return render_template('result.html', result=name)
def get_recipe(image_bytes): a=[] b=[] c=[] len1=[] len2=[] tensor = get_tensor(image_bytes) greedy = [True, False, False, False] beam = [-1, -1, -1, -1] temperature = 1.0 numgens = len(greedy) for i in range(numgens): with torch.no_grad(): outputs = model.sample(tensor, greedy=greedy[i],temperature=temperature, beam=beam[i], true_ingrs=None) ingr_ids = outputs['ingr_ids'].cpu().numpy() recipe_ids = outputs['recipe_ids'].cpu().numpy() data_dir = 'M:/Final Project/code/inversecooking-master/data' ingrs_vocab = pickle.load(open(os.path.join(data_dir, 'ingr_vocab.pkl'), 'rb')) vocab = pickle.load(open(os.path.join(data_dir, 'instr_vocab.pkl'), 'rb')) outs, valid = prepare_output(recipe_ids[0], ingr_ids[0], ingrs_vocab, vocab) len1.append(len(outs['ingrs'])) len2.append(len(outs['recipe'])) a.append(outs['title']) b.append(outs['ingrs']) c.append(outs['recipe']) return a,b,c,len1,len2
def get_rice_name(image_bytes): tensor = get_tensor(image_bytes) outputs = model.forward(tensor) _, prediction = outputs.max(1) category = prediction.item() rice_name = idx_to_class[category] return category, rice_name
def get_blood_type(image_bytes): tensor = get_tensor(image_bytes) outputs = model.forward(tensor) _, prediction = outputs.max(1) category = prediction.item() class_idx = idx_to_class[category] blood_type = [class_idx] return category, blood_type
def prediction(image_bytes): tensor = get_tensor(image_bytes) outputs = model(tensor) _, prediction = outputs.max(1) category = prediction.item() emotion = class_names[category] return emotion
def get_response_image(image_bytes): tensor = get_tensor(image_bytes) outputs = model.forward(tensor) ## how exactly do i interact with the model here? ie. inputs/outputs ## return segmented image return output_image
def get_disease_name(image_bytes): tensor = get_tensor(image_bytes) outputs = model(tensor) _, prediction = outputs.max(1) category = prediction.item() disease_name = class_names[category] return disease_name
def get_class_name(image_bytes) : tensor=get_tensor(image_bytes) output= model(tensor) _,preds_tensor = torch.max(output,1) preds = np.squeeze(preds_tensor.numpy()) classes=['LeafBlast', 'BrownSpot', 'Healthy', 'Hispa'] category=classes[preds] return category
def get_flower_name(image_bytes): tensor = get_tensor(image_bytes) outputs = model.forward(tensor) _, prediction = outputs.max(1) category = prediction.item() class_idx = idx_to_class[category] flower_name = cat_to_name[class_idx] return category, flower_name
def get_flower_name(image_bytes): tensor = get_tensor(image_bytes) outputs = model.forward(tensor) #print(outputs) _, prediction = outputs.max(1) category = prediction.item() flower_name = cat_to_name[idx_to_class[category]] return flower_name, category
def get_cuisine_name(image_bytes): tensor = get_tensor(image_bytes) model_cuisine.eval() outputs = model_cuisine.forward(tensor) _, prediction = outputs.max(1) category = prediction.item() class_idx_cuisine = idx_to_class_cuisine[category] cuisine_name = cuisine_cat_to_name[class_idx_cuisine] return category, cuisine_name, outputs
def get_cash_name(image_bytes): tensor = get_tensor(image_bytes) model.eval() outputs = model.forward(tensor) _, prediction = outputs.max(1) category = prediction.item() class_idx = idx_to_class[category] cash_name = cat_to_name[class_idx] return category, cash_name, outputs
def get_flower_name(image_bytes) : tensor=get_tensor(image_bytes) outputs=model.forward(tensor) print(outputs) a,prediction = outputs.max(1) category=prediction.item() trainset=torchvision.datasets.ImageFolder('train/') category=trainset.classes[prediction.item()] return category
def hello_world(): if request.method == 'GET': return render_template('index.html', value='hi') if request.method == 'POST': print(request.files) if 'file' not in request.files: print('file not uploaded') return file = request.files['file'] image = file.read() top_probs, top_labels, top_fruits = get_fruit_name(image_bytes=image) #prediction, probs = get_fruit_name(image_bytes=image) get_fruit_name(image_bytes=image) tensor = get_tensor(image_bytes=image) print(get_tensor(image_bytes=image)) return render_template('result.html', fruits=top_fruits, name=top_labels, probabilities=top_probs)
def get_prediction(image_bytes): try: tensor_img = get_tensor(image_bytes) outputs = model.forward(tensor_img) except Exception: return 0, 'error!' conf, prediction = outputs.max(1) pet_class = prediction.item() pet_name = class_to_name[str(pet_class)] return pet_class, pet_name
def upload_file_cuisine(): results = [] if request.method == 'GET': return render_template('upload_file.html') if request.method == 'POST': if "file" not in request.files: print("File not uploaded.") return file = request.files['file'] image = file.read() tensor = get_tensor(image_bytes=image) category, cuisine, output = get_cuisine_name(image_bytes=image) print(get_tensor(image_bytes=image)) for the_cuisine in cuisines: if the_cuisine["cuisine_name"] == cuisine: results.append(the_cuisine) return jsonify(results)
def get_class_name(image_bytes): """ Get image bytes from an image, turn them to a tensor and predict the right class for this tensor. :param image_bytes: :return: class's id (int) and class's name (string). """ tensor = get_tensor(image_bytes) outputs = model.forward(tensor) _, prediction = outputs.max(1) pred_class = prediction.item() class_name = cat_to_name[str(pred_class)] return pred_class, class_name
def get_flower_name(image_bytes): tensor = get_tensor(image_bytes) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.eval() with torch.no_grad(): out = model(tensor.to(device)) ps = torch.exp(out) top_p, top_class = ps.topk(1, dim=1) index = top_class.item() return class_names[index] '''outputs = model.forward(tensor)
def get_flower_name(image_bytes, file): tensor = get_tensor(image_bytes, file) outputs = model.forward(tensor) _, prediction = outputs.max(1) category = prediction.item() print(category) class_idx = idx_to_class[category] flower_name = cat_to_name[class_idx] # file. # save('flowers_1.jpg') flower_name = flower_name[0].upper() + flower_name[1:] return category, flower_name
def classify(img): # convert image to tensor img = get_tensor(img).cuda() # load saved model net = torch.load('saveModel.pth') # push image through network outputs = net(img).cuda() _, predicted = torch.max(outputs.data, 1) # connect prediction result to corresponding class result = classes[predicted[0]] return result
def get_speaker_embedding(file_path, preprocess=True, sampling_rate=8000, duration=None, normalize=True): ref_audio = get_tensor(file_path, preprocess=preprocess, sampling_rate=sampling_rate, duration=duration) embed, partial_embeds, _ = encoder.embed_utterance(ref_audio, return_partials=True) if (normalize): embed = embed / np.linalg.norm(embed) return embed
def prediction(image_bytes): tensor = get_tensor(image_bytes) outputs = model.forward(tensor) # Probs probs = F.softmax(outputs, dim=1) # Top probs top_probs, top_labs = probs.topk(k=3) top_probs = top_probs.detach().numpy().tolist()[0] top_labs = top_labs.detach().numpy().tolist()[0] # Convert indices to classes idx_to_class = {val: key for key, val in class_to_idx.items()} top_labels = [idx_to_class[lab] for lab in top_labs] top_diseases = [cat_to_name[idx_to_class[lab]] for lab in top_labs] return top_probs, top_labels, top_diseases
def get_cat_name(image_location): # prediction model.eval() with torch.no_grad(): tensor = get_tensor(image_location) outputs = model.forward(tensor) prediction = outputs.argmax(1) # ambil nilai terbesar category = prediction.item() # ambil itemnya topk = 3 # rank prediksi probabilities = torch.exp(outputs).data.to( torch.float32) # convert log >> exp probabilities = (probabilities * 100) prob = torch.topk(probabilities, topk)[0].tolist()[0] # probabilities index = torch.topk(probabilities, topk)[1].tolist()[0] # index ind = [] for i in range(len(class_to_idx.items())): ind.append(list(class_to_idx.items())[i][0]) # transfer index to label label = [] for i in range(3): label.append(ind[index[i]]) max_index = np.argmax(prob) max_probability = prob[max_index] labels = cat_to_name[category] max_probability = "{: .2f}".format(max_probability) # ambil nilai array list classes0 = label[0] classes1 = label[1] classes2 = label[2] prob0 = "{: .2f}".format(prob[0]) prob1 = "{: .2f}".format(prob[1]) prob2 = "{: .2f}".format(prob[2]) total = "{: .1f}".format(float(prob0) + float(prob1) + float(prob2)) return labels, max_probability, classes0, classes1, classes2, prob0, prob1, prob2, total, image_location
def predict(): if request.method == 'POST': if 'image' in request.files: try: image = request.files['image'].read() batch = get_tensor(image) except Exception as err: print(err.args) return make_response( jsonify({'Error': 'Upload valid image file'}), 400) output = model(batch) pos = np.mean(output[0].cpu().data.numpy().copy(), axis=0) qtn = np.mean(output[1].cpu().data.numpy().copy(), axis=0) result = {'position': pos.tolist(), 'quaternion': qtn.tolist()} return make_response(jsonify(result), 200) else: return make_response(jsonify({'Error': 'Missed image in request'}), 400)
def hello_world(): if request.method == 'GET': return render_template('index1.html', value='hi') if request.method == 'POST': print(request.files) if 'file' not in request.files: print('file not uploaded') return file = request.files['file'] image = file.read() flower_name= get_flower_name(image_bytes=image) get_flower_name(image_bytes=image) tensor = get_tensor(image_bytes=image) #print(get_tensor(image_bytes=image)) #train_dir = 'dogImages/train' #path1=train_dir+'/'+imgclass #path2=os.listdir(path1)[0] #pathx=imgclass+'/'+path2 #path3=path1+'/'+path2 #yy='../'+path3 #b = f'"{yy}"' #y= '<img src='+b+'>' return render_template('result.html', flower=flower_name)
def generate_image(uploaded_img): prod_img = get_tensor(uploaded_img) prod_labels = torch.Tensor([[0, 0, 0, 0, 0]]) img = prod_img[0] label = prod_labels[0] imgs = img.repeat(c_dim, 1, 1, 1) # imgs shape = [5, 3, 128, 128] labels = label.repeat(c_dim, 1) # labels shape = [5, 5] for sample_i, changes in enumerate(label_changes): for col, val in changes: labels[sample_i, col] = 1 - labels[sample_i, col] if val == -1 else val gen_imgs = generator(imgs, labels) # gen_imgs = torch.cat([x for x in gen_imgs.data], -1) # img_sample = torch.cat((img.data, gen_imgs), -1) # img_sample = F.to_pil_image(img_sample) save_image(gen_imgs, 'static/prod.png', normalize=True) return gen_imgs
def upload_file(): results = [] if request.method == 'GET': return render_template('upload_file_cash.html') if request.method == 'POST': if "file" not in request.files: print("File not uploaded.") return preferred_currency = "USD" file = request.files['file'] image = file.read() tensor = get_tensor(image_bytes=image) category, cash, output = get_cash_name(image_bytes=image) converted_value = converter.convert(int(cash), "NPR", preferred_currency) for the_cash_value in cash_values: if the_cash_value["NepaliValue"] == cash: the_cash_value["ConvertedValue"] = round(converted_value, 3) results.append(the_cash_value) return jsonify(results)
def flower_classify(): if request.method == 'GET': return render_template('index.html') if request.method == 'POST': print(request.files) if 'file' not in request.files: print('file not uploaded') return file = request.files['file'] filename = secure_filename(file.filename) pic_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(pic_path) file.seek(0) image = file.read() #category, flower_name = get_flower_name(image_bytes=image) tensor = get_tensor(image_bytes=image) top_flower_name, flowers, probs = predict(tensor) rounded_probs = list(np.around(np.array(probs), 2)) return render_template('bar_chart.html', pic_path=pic_path, title=top_flower_name, max=1, labels=flowers, values=rounded_probs)