我创建了一个预测皮肤病变的模型。训练后,我将权重保存到model.h5文件中。我有一个带有电报集成代码的预测脚本和app.py。我可以通过命令启动我的机器人,加载测试图片,但我看不到显示结果。我可以运行机器人,但不会在屏幕上返回结果
from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
ConversationHandler)
import logging
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
import sys
import time
import random
import datetime
import json
import requests
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
from firebase_admin import storage
import cv2
import sys
import pytesseract
import os
from datetime import date
from collections import deque
from bs4 import BeautifulSoup
from urlparse import urljoin
import sys
import urllib2
from predict import predict_class
import matplotlib.pyplot as plt
import copy
import numpy as np
from keras.models import load_model
import tensorflow as tf
import keras.losses
from keras.metrics import categorical_accuracy, top_k_categorical_accuracy
from keras.preprocessing import image
logging.basicConfig(filename='beaconing_bot.log', filemode='w',format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
GET_OPTION, PHOTO, LOCATION, PROCESS, END_SESSION = range(5)
flag = 0
queue = deque([])
visited_list = []
image_size = 224
global graph, sess
dis_classes = {
0:'Actinic Keratoses',
1:'Basal Cell Carcinoma',
2:'Benign Keratosis',
3:'Dermatofibroma',
4:'Melanoma',
5:'Melanocytic Nevi',
6:'Vascular Lesions'
}
graph = tf.Graph()
sess = tf.Session(graph = graph)
model = load_model('model.h5', compile = False)
def start(bot, update):
global user_name
user_name = update.message.from_user
keyboard = [[InlineKeyboardButton("UPLOAD", callback_data='upload'),
InlineKeyboardButton("Depth First Search", callback_data='dfs')]]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text('Hi %s! I am DoctorOnCall Bot. Send /cancel to stop session.\n\nPlease, choose below:' % (user_name['first_name']), reply_markup=reply_markup)
print(update)
return GET_OPTION
def get_option(bot, update):
query = update.callback_query
print(query)
if query.data == 'upload':
bot.edit_message_text(text="Please upload the picture of infected area",
chat_id=query.message.chat_id,
message_id=query.message.message_id)
return PHOTO
elif query.data == 'dfs':
bot.edit_message_text(text="Breath First Search selected. Please, supply me with the website you want to crawl",
chat_id=query.message.chat_id,
message_id=query.message.message_id)
algorithm = 'dfs'
return GET_URL
def photo(bot, update):
global create_at
global picture_name
datetime.datetime.fromtimestamp(int(time.time())).strftime('%Y_%m_%d__%H_%M_%S')
photo_file = bot.get_file(update.message.photo[-1].file_id)
#photo_file.download('infected_image.jpg')
picture_name = update.message.photo[-1].get_file().download('./input_img/' + str(update.message.chat_id) + '.jpg')
update.message.reply_text('Awesome! I got the picture. Now send me your location.')
return LOCATION
def location(bot, update):
global latitude
global longitude
latitude = update.message.location.latitude
longitude = update.message.location.longitude
update.message.reply_text('Awesome! Now I know where you at. Press /begin to start diagnosis')
Z
return PROCESS
def process(bot, update):
print(picture_name)
test_image = image.load_img(img, target_size = (image_size, image_size))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = model.predict(test_image * 100.0).round(2)
#training_set.class_indice
new_dict = {
dis_classes[0]: result[0][0],
dis_classes[1]: result[0][1],
dis_classes[2]: result[0][2],
dis_classes[3]: result[0][3],
dis_classes[4]: result[0][4],
dis_classes[5]: result[0][5],
dis_classes[6]: result[0][6]
}
dict_dis = sorted(new_dict.items(), key=lambda x: x[1], reverse=True)
print(dict_dis)
dict_dis = dict(sorted(new_dict.items(), key=lambda x: x[1], reverse=True)[:3])
max_val = max(dict_dis, key=dict_dis.get)
plt.bar(range(len(dict_dis)), list(dict_dis.values()), align='center')
x1,x2,y1,y2 = plt.axis()
plt.axis((x1,x2,0,1))
plt.xticks(range(len(dict_dis)), range(len(dict_dis)))
plt.savefig('./temp/plots/tempfig.png')
update.message.reply_text("Thank you!\n \nYou will recieve your report Soon")
bot.send_photo(chat_id=update.message.chat_id, photo=open('./temp/plots/tempfig.png', 'rb'))
os.remove('./temp/plots/tempfig.png')
plt.cla()
keys = list(dict_dis.keys())
message_text = '0 ->' + str(keys[0]) + '\n1 ->' + str(keys[1]) + '\n2 ->' + str(keys[2])
update.message.reply_text("Results are as follows: %s" % (message_text))
print(message_text)
return END_SESSION
def done(bot, update):
update.message.reply_text('Thank you! :) . Bye!!!')
return ConversationHandler.END
def cancel(bot, update):
update.message.reply_text('Bye! You cancelled the session',
reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END
def error(bot, update, error):
logger.warning('Update "%s" caused error "%s"', update, error)
def main():
updater = Updater("807487613:AAHkdroQt8josGco1Ct938qXe1_OvGd9E3M")
dp = updater.dispatcher
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
GET_OPTION: [CallbackQueryHandler(get_option)],
PHOTO: [MessageHandler(Filters.photo, photo)],
LOCATION: [MessageHandler(Filters.location, location)],
PROCESS: [CommandHandler('begin', process)],
END_SESSION: [CommandHandler('done', done)]
},
fallbacks=[CommandHandler('cancel', cancel)]
)
dp.add_handler(conv_handler)
dp.add_error_handler(error)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()