def index(): now_timestamp = datetime.now() if request.method == 'POST': uploaded_file = request.files['file'] if uploaded_file.filename != '': image_path = os.path.join('static', uploaded_file.filename) uploaded_file.save(image_path) rs = model.get_prediction(image_path) result = { 'class_name': rs["class_name"], 'percentage': rs["percentage"], 'image_path': image_path, } filename_data_save = image_path predict_class = rs["class_name"] percentage = rs["percentage"] tomato_ref.document().set({'percentage': percentage, 'predict_class': predict_class, 'file_path': filename_data_save, 'timestamp': str(datetime.timestamp(now_timestamp))}) return render_template('result.html', result=result) query = tomato_ref.order_by( 'timestamp', direction=firestore.Query.DESCENDING).limit(5) results = query.stream() data_dict_history = {} for doc in results: data_dict_history[doc.get('timestamp')] = [doc.get( 'file_path'), doc.get('predict_class'), doc.id,doc.get('percentage')] return render_template('index.html', result_dict=data_dict_history)
def predict(): if request.methods='POST': file = request.files[file] # img reader img_bytes = file.read() class_id, class_name = get_prediction(image_bytes=img_bytes) return jsonify({'class_id':class_id, 'class_name':class_name})
def parse_vk(bot, update): wall_data = [] logger.info("Start parsing vk") for public_id in VK_PUBLICS_LIST: wall_data += get_public_updates(public_id, 10) time.sleep(0.5) logger.info("End parsing vk") for post in wall_data: if 'attachments' in post: items = filter(lambda item: item['type'] == "photo", post['attachments']) img_links = [item['photo'].get('photo_604', "") for item in items] img_links = list(filter(lambda x: x != "", img_links)) if len(img_links): timestamp = post['date'] * 1000 text = post['text'] public_id = -post['from_id'] post_id = post['id'] s = process_text_vk(text) if s and db.flats.find({"text": s}).limit(1).count() == 0: img_paths = [save_img(link) for link in img_links] classes = [] for img_path in img_paths: classes.append(get_prediction(img_path)) if any([c == 1 for c in classes]): post_id = db.flats.insert_one({ "text": s, "link": f"https://vk.com/wall-{public_id}_{post_id}", "from": "vk", "sent": False, }).inserted_id else: logger.info(f"{post_id} is not center room") send_messages(bot)
def index(): if request.method == 'POST': name = request.form['name'] name_object = db_models.Name(name=name) gender_number = model.get_prediction(model_names, name) if gender_number: name_object.gender_predict = 'Male' else: name_object.gender_predict = 'Female' db.session.add(name_object) db.session.commit() return redirect(url_for('view_prediction', id=name_object.id)) return render_template('index.html')
def chat_output(): data = request.get_json(force=True) #input text sent via POST request input_text = data["input"] #Prediction np array tag_pred = get_prediction([bagOfWords(input_text, words).tolist()]) #Corresponding tag output chatOut_index = np.argmax(tag_pred) #Equivalent tag for the predicted index tag = sorted_classes[chatOut_index] #Getting the data for the corresponding tag in the JSON intents = json_data["intents"] reply = "" # confidence = chatOut[chatOut_index] #Loop to randomly choose a reply for the corresonding tag for i in range(len(intents)): if intents[i]["tag"] == tag: responses = intents[i]["responses"] reply = np.random.choice(responses, 1, replace=False)[0] result = {"reply": reply} response = jsonify(result) # response.headers.add('Access-Control-Allow-Origin', '*') return response
def predict(): if request.method == "POST": request_json = request.get_json() predict_freq = request_json['predict_freq'] duration = request_json['duration'] response = get_prediction(predict_freq, duration) return Response(response, mimetype='application/json')
def update_output(n, list_of_names): if n is not None: # process current_img = os.path.join(IMG_DIR, list_of_names[0]) new_name = "new_" + list_of_names[0] pred = get_prediction(gen, current_img) print(pred.size) # remove the original uploaded image since we're done using it os.remove(current_img) pred.save(os.path.join(IMG_DIR, new_name)) return parse_contents(os.path.join(IMG_DIR, new_name))
def make_prediction(): if request.method == 'POST': sentence = request.values.get('sentence') prediction = model.get_prediction(sentence) print(prediction) result = { 'class_name': prediction, 'sentence': sentence, } print(result) return result
def make_prediction(): if request.method == 'POST': # get uploaded image file if it exists file = request.files['image'] if not file: return render_template('index.html', label="No file") img_bytes = file.read() class_id, class_name = get_prediction(image_bytes=img_bytes) return render_template('index.html', label=str(class_name))
def upload_file(): if request.method == 'POST': uploaded_file = request.files['file'] if uploaded_file.filename != '': image_path = os.path.join('static', uploaded_file.filename) uploaded_file.save(image_path) class_name = model.get_prediction(image_path) result = { 'class_name': class_name, 'image_path': image_path, } return result
def index(): if request.method == 'POST': # getting the loaded file uploaded_file = request.files['file'] # getting the state and county they are from to provide info about pest control companies state = request.form['state'] county = request.form['county'] # only there is a file that we go to the result page if uploaded_file.filename != '': image_path = os.path.join('static/images', uploaded_file.filename) uploaded_file.save(image_path) class_name = model.get_prediction(image_path) result = { 'class_name': class_name, 'image_path': image_path, } # getting the state result db = get_db() companies = db.execute( 'SELECT * FROM companies WHERE state=? AND county= ?', ( state, county, )).fetchall() # get the product category belonging to the bug #categories = db.execute('SELECT category FROM bug_category WHERE bug= ?',(class_name,)).fetchall() situations_categories = db.execute( 'SELECT situation,category FROM bug_category WHERE bug= ?', (class_name, )).fetchall() # getting the info about the bug bite info = db.execute('SELECT * FROM info WHERE bug = ?', (class_name, )).fetchall() # make empty list and then extend to combine the products conditions = [] for row in situations_categories: category = row[1] product = db.execute( 'SELECT * FROM products WHERE category = ? ORDER BY RANDOM() LIMIT 1', (category, )).fetchall() conditions.append([row[0], category, product]) # returning the result template return render_template('result.html', info=info, result=result, companies=companies, conditions=conditions) return render_template('index.html')
def main(): st.title("shopee test") image_file = st.file_uploader("upload an image here", type=["jpg", "jpeg", "png"]) if image_file is None: st.write('upload image here') else: image_tensor, image_pil = load_image(image_file) prediction = get_prediction( image_tensor ) # TODO: prediction[1] flatten, numpy.array, normalize st.write(f"prediction result: {prediction[0]}, prob: {prediction[1]}") st.image(image_file, use_column_width=True)
def index(): if request.method == 'POST': uploaded_file = request.files['file'] if uploaded_file.filename != '': image_path = os.path.join('static', uploaded_file.filename) uploaded_file.save(image_path) class_name = model.get_prediction(image_path) result = { 'class_name': class_name, 'image_path': image_path, } return render_template('result.html', result=result) return render_template('index.html')
def random_adjacency_matrix_with_model(length, hour, minute): tab = np.zeros([length, length], dtype=float) for i in range(length): for j in range(length): if (i == j): break # Max 500 vertices pred = get_prediction((i + j) % 500, hour, minute) tab[i][j] = pred tab[j][i] = pred return tab
def submit_file(): if request.method == 'POST': # File not in the request if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # File not selected if file.filename == '': flash('No file selected for uploading') return redirect(request.url) # Handle invalid file type extensions if not allowed_file(file.filename): flash( 'Invalid file type. Allowed image types are -> png, jpg, jpeg') return redirect(request.url) # File uploaded if file and allowed_file(file.filename): # Get file name filename = secure_filename(file.filename) # Save picture file.save(os.path.join(UPLOAD_FOLDER, filename)) # Predict get_prediction(os.path.join(UPLOAD_FOLDER, filename)) class_name, accuracy_percent = get_prediction(filename) # Send messages to front end template flash(class_name) flash(accuracy_percent) flash(filename) return render_template('index.html', filename=filename)
def process_form(): formData = request.values if request.method == "GET" else request.values user_input = [] for item in formData.items(): user_input.append(item[1]) # response = "Form Contents <pre>%s</pre>" % "<br/>\n".join(["%s:%s" % item for item in formData.items()]) # return response for item in formData.items(): if item[0] == 'fixed-acidity': user_input[0] == item[1] if item[0] == 'volatile-acidity': user_input[1] == item[1] if item[0] == 'citric-acid': user_input[2] == item[1] if item[0] == 'residual-sugar': user_input[3] == item[1] if item[0] == 'chlorides': user_input[4] == item[1] if item[0] == 'free-sulfur-dioxide': user_input[5] == item[1] if item[0] == 'total-sulfur-dioxide': user_input[6] == item[1] if item[0] == 'density': user_input[7] == item[1] if item[0] == 'pH': user_input[8] == item[1] if item[0] == 'sulphates': user_input[9] == item[1] if item[0] == 'alcohol': user_input[10] == item[1] response = get_prediction(user_input) print(user_input) if response == '2': return render_template('rating.html', rating='AVERAGE') elif response == '1': return render_template('rating.html', rating='POOR') elif response == '3': return render_template('rating.html', rating='EXCELLENT') else: return render_template( 'rating.html', rating='Something went wrong. Please try again.')
def movie_info(movieid): """Shows available info for given user""" movie = Movie.query.filter_by(movie_id=movieid).one() ratings = Rating.query.filter_by(movie_id=movieid).all() if 'user' in session: user = session['user'] prediction = get_prediction(user, movieid) eye_rating = eye_prediction(movieid) user_rating = Rating.query.filter( (Rating.user_id == user) & (Rating.movie_id == movieid)).first() return render_template('movie.html', movie=movie, ratings=ratings, user_rating=user_rating, prediction=prediction, eye_rating=eye_rating)
def parse_avito(bot, update): logger.info("Start parsing avito") feed = get_avito_feed() for item in feed: s = process_text_avito(item['text']) date = datetime.datetime.strptime(item['updated'], "%Y-%m-%dT%H:%M:%SZ") timestamp = int(date.timestamp()) timedelta = datetime.datetime.now() - date if s and timedelta.days < 1 and check_duplicates(s): img_paths = [save_img(link) for link in item['img_links']] classes = [] for img_path in img_paths: classes.append(get_prediction(img_path)) if any([c == 1 for c in classes]): post_id = db.flats.insert_one({ "text": s, "link": item['link'], "from": "avito", "sent": False, }).inserted_id logger.info("End parsing avito") send_messages(bot)
# 将数组转化为float32型 image_dst_array = np.array(image_dst_array, dtype=np.float32) return image_dst_array # 定义各种变量 train_size = 16 test_size = 400 # 定义占位符 image_placeholder = tf.placeholder(tf.float32, [None, 200, 200, 3]) # 100*100 # 构建神经网络 prediction = model.get_prediction(image_placeholder) # 创建保存器 saver = tf.train.Saver() # 导入图片 filepath = input('Please input the path of your image:') # 加载图片 image_jpg = Image.open(filepath) image = imagenormalize(image_jpg) image_input = np.array(image).reshape((1, 200, 200, 3)) with tf.Session(config=config) as sess: saver.restore(sess, 'cnn_save/cnn_save.ckpt')
import time from cli_parser import get_parser from model import get_prediction if __name__ == '__main__': parser = get_parser() args = parser.parse_args() sentence = vars(args)['Tweet'] start_time = time.time() prediction, prediction_time = get_prediction(' '.join(sentence)) print(f"Prediction: {prediction}.") print(f'Total time spent: {round(time.time() - start_time, 3)} seconds.') print(f'Time for prediction: {round(prediction_time, 3)} seconds.')
def predict(): if request.method == 'POST': file = request.files['image'] img_bytes = file.read() low, mlow, middle, mhigh, high, other = get_prediction(image_bytes=img_bytes) return jsonify({'低收入': low, '中低收入': mlow, '中等收入': middle, '中高收入': mhigh, '高收入': high, '其他': other,})
def predict(): if request.method == 'POST': file = request.files['file'] img_bytes = file.read() class_id, class_name = get_prediction(img_bytes) return jsonify({'class_id': class_id, 'class_name': class_name})
def index(): if request.method == 'POST': uploaded_file = request.files['file'] filename = uploaded_file.filename if filename != '': if uploaded_file.filename[-3:] in ['zip']: if not os.path.isdir(OUTPUT_DIR): os.mkdir(OUTPUT_DIR) image_path = os.path.join(OUTPUT_DIR, filename) uploaded_file.save(image_path) with zipfile.ZipFile(image_path, 'r') as zip_ref: zip_ref.extractall(OUTPUT_DIR) img_dir = OUTPUT_DIR + "/" + filename[:-4] dicom_paths = model.get_dicom_paths(img_dir) pet_scan = model.get_pet_scan(dicom_paths) prediction = model.get_prediction(pet_scan) if prediction[1] > 0.5: diagnosis = 'Alzheimer\'s Disease' else: diagnosis = 'Cognitively Normal' classidx = np.argmax(prediction) heat_map = model.compute_saliency_map(pet_scan, classidx=classidx) fig = model.create_plot(pet_scan, heat_map) fig_json = json.dumps({ 'data': json.loads( json.dumps(fig.data, cls=plotly.utils.PlotlyJSONEncoder)), 'layout': json.loads( json.dumps(fig.layout, cls=plotly.utils.PlotlyJSONEncoder)) }) empty_folder(OUTPUT_DIR) return render_template('show.html', prediction=np.round( prediction[classidx], decimals=2), diagnosis=diagnosis, plot_json=fig_json) #else: #url = 'https://drive.google.com/uc?export=download&id=1DaL2KOLAZ616MFPOgwCQdqEeoUFi2cRa' #urllib.request.urlretrieve(url, 'file.zip') #with zipfile.ZipFile('file.zip', 'r') as zip_ref: # zip_ref.extractall(OUTPUT_DIR) #os.remove('file.zip') ##img_dir = glob.glob(OUTPUT_DIR + '/*')[1] #img_dir = OUTPUT_DIR + '/I257156' #dicom_paths = model.get_dicom_paths(img_dir) #pet_scan = model.get_pet_scan(dicom_paths) #prediction = model.get_prediction(pet_scan) #if prediction[1] > 0.5: # diagnosis = 'Alzheimer\'s Disease' #else: # diagnosis = 'Cognitively Normal' #classidx = np.argmax(prediction) #heat_map = model.compute_saliency_map(pet_scan, classidx = classidx) #fig = model.create_plot(pet_scan, heat_map) #redata = json.loads(json.dumps(fig.data, cls=plotly.utils.PlotlyJSONEncoder)) #relayout = json.loads(json.dumps(fig.layout, cls=plotly.utils.PlotlyJSONEncoder)) #fig_json=json.dumps({'data': redata,'layout': relayout}) #empty_folder(OUTPUT_DIR) #return render_template('show.html', prediction = 0.84, diagnosis = 'Alzheimer\'s Disease', plot_json = fig_json) return render_template('index.html')