从容器:本地主机读取资源变量预测/内核时出错

时间:2019-11-09 07:59:35

标签: python

tensorflow.python.framework.errors_impl.FailedPreconditionError: Error while reading resource variable predictions/kernel from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/predictions/kernel)
             [[{{node predictions/MatMul/ReadVariableOp}}]]

这是我的代码:

import pandas as pd
import os
import json
import numpy as np
from keras.applications.imagenet_utils import preprocess_input, decode_predictions
from keras.preprocessing.image import img_to_array, load_img  #ImageDataGenerator, array_to_img
from keras.models import load_model #Sequential
import base64
import tensorflow as tf
global graph,model
graph = tf.get_default_graph()
import ssl
try:
    import httplib  # Python 2
except:
    import http.client as httplib  # Python 3
path = os.path.dirname(os.path.abspath(__file__))
path = path[0:-4]
modelpath = os.path.join(path, r'static/models')
#Loading models # Slower 
VGG16_model = load_model(str(modelpath) + '/vgg16.h5')
print ("VGG16_model loaded")
DamgeDetection_model = load_model(str(modelpath) + '/car_damage-model_retrained.h5')
print ("DamgeDetection_model loaded")
location_model = load_model(str(modelpath) + '/carLocationWithfrontAndBack3400Images.h5')
print ("Location model loaded")
severity_model = load_model(str(modelpath)+ '/car_damage_severity.h5')
print ("Severity model loaded")

def prepare_img_224(img_path):
    img = load_img(img_path, target_size=(224, 224))
    x = img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    return x

def prepare_img_128(img_path):
    img = load_img(img_path, target_size=(128 , 128))
    x = img_to_array(img)
    x = x.reshape((1,) + x.shape)/64
    return x

#validating provided image is car
def car_categories_gate(img_224, model):
    print ("Validating that this is a picture of your car...")
    with graph.as_default():
        out = model.predict(img_224)
        carList =['sports_car', 'minivan', 'grille', 'convertible', 'racer', 'beach_wagon', 'jeep', 'pickup', 'minibus', 
              'limousine', 'golfcart', 'cab', 'car_wheel', 'ambulance', 'police_van', 'Model_T', 
              'tow_truck', 'trailer_truck', 'coffeepot', 'car_mirror', 'snowmobile','chain_saw', 'snowplow',
              'fire_engine', 'recreational_vehicle', 'waffle_iron', 'harmonica', 'backpack', 
              'steam_locomotive', 'ashcan', 'espresso_maker', 'buckle', 'water_jug', 'projector',
              'seat_belt', 'motor_scooter',  'mailbox', 'tractor', 'moving_van', 'amphibian','half_track','garbage_truck','tank']
        label = decode_predictions(out)
        predicted_List = label[0]
        setFlagForImageDetection = False
        for tupleX in predicted_List:
            if setFlagForImageDetection == True:
                return True 
            else:
                for classNames in carList:
                    if classNames in tupleX[1]:
                        setFlagForImageDetection  = True              
                        return True

        if setFlagForImageDetection == False:
            return False

def prepare_img_256(img_path):
    img = load_img(img_path, target_size=(256, 256)) # this is a PIL image 
    x = img_to_array(img) # this is a Numpy array with shape (3, 256, 256)
    x = x.reshape((1,) + x.shape)/255
    return x

def car_damage_gate(img_256, model):
    print ("Validating that damage exists...")
    with graph.as_default():
        pred = model.predict(img_256)
        if pred[0][0] < 1:
            return True # print "Validation complete - proceed to location and severity determination"
        else:
            return False
def location_assessment(img_128, model):
    print ("Determining location of damage...")
    with graph.as_default():
#    pred = model.predict(img_128)
        prediction = model.predict(img_128)
    #    print(prediction[0])
        if prediction[0][0] <=.9:
    #        print("Front Part Of car")
            return "Front Part Of car"
        else:
            return"Rear Part Of vehicle"
def severity_assessment(img_256, model):
    print("Determining severity of damage...")
    with graph.as_default():
        pred_severe = model.predict(img_256)
        pred_label = np.argmax(pred_severe, axis=1)
        d = {0: 'Minor', 1: 'Moderate', 2: 'Severe'}
        for key in d:
            if pred_label[0] == key:
                return "{} ".format(d[key])

def engine(img_path , userid):
#    with graph.as_default():
#        VGG16_model = load_model(str(modelpath) + '/vgg16.h5')
#        print ("VGG16_model loaded")
    img_224 = prepare_img_224(img_path)
    g1 = car_categories_gate(img_224, VGG16_model)
#    g1 = True
    print(g1)
    if g1 is False:
        result = {'gate1': 'Car validation check: ', 
        'gate1_result': 0, 
        'gate1_message': {0: 'Are you sure this is a picture of your car? Please retry your submission.', 
        1: 'Hint: Try zooming in/out, using a different angle or different lighting'},
        'gate2': None,
        'gate2_result': None,
        'gate2_message': {0: None, 1: None},
        'location': None,
        'severity': None,
        'final': 'Damage assessment unsuccessful!'}
        return result


#    #Car Make model and number 
    print('***************start****************************')
    headers = {"Content-type": "application/json","X-Access-Token": "rI0eHteykKhi6Rh9L46ujqELNCsh6wK4WOPy"}
    conn = httplib.HTTPSConnection("dev.sighthoundapi.com",context=ssl.SSLContext(ssl.PROTOCOL_TLSv1))

# To use a hosted image uncomment the following line and update the URL
#image_data = "http://www.blogcdn.com/www.autoblog.com/media/2011/08/lead2-2012-toyota-camry-se-fd.jpg"

# To use a local file uncomment the following line and update the path


    image_data = base64.b64encode(open(img_path, "rb").read()).decode()

    params = json.dumps({"image": image_data})
    print('********')
    conn.request("POST", "/v1/recognition?objectType=vehicle,licenseplate", params, headers)
    print('****hagshj****')
    response = conn.getresponse()
    result = response.read()
    vehicleJsonOut = json.loads(result)
    print('***************stop****************************')

    makeOfvehicle = ''
    modelOfVehicle = ''
    typeOfVehicle = ''
    numberOfvehicle = ''
    regionofVehicle = ''
    colorOfVehicle = ''
    numberPlateFound = 0
    resultfoundFlag = True
    try:
        vehicleJsonOut['objects'][0]['vehicleAnnotation']
    except:
        resultfoundFlag = False


    if resultfoundFlag == True:
        if 'attributes' in vehicleJsonOut['objects'][0]['vehicleAnnotation']:
            makeOfvehicle = vehicleJsonOut['objects'][0]['vehicleAnnotation']['attributes']['system']['make']['name']
            modelOfVehicle = vehicleJsonOut['objects'][0]['vehicleAnnotation']['attributes']['system']['model']['name']
            typeOfVehicle = vehicleJsonOut['objects'][0]['vehicleAnnotation']['attributes']['system']['vehicleType']
            colorOfVehicle = vehicleJsonOut['objects'][0]['vehicleAnnotation']['attributes']['system']['color']['name']
            print("Make of vehicle: " + makeOfvehicle ) 
            print('Model of vehicle: ' +  modelOfVehicle)
            print('Vehiicle type : '  + typeOfVehicle)
            print('vehicle color : ' + colorOfVehicle )

        if 'licenseplate' in vehicleJsonOut['objects'][0]['vehicleAnnotation']:
            numberOfvehicle = vehicleJsonOut['objects'][0]['vehicleAnnotation']['licenseplate']['attributes']['system']['string']['name']
            regionofVehicle = vehicleJsonOut['objects'][0]['vehicleAnnotation']['licenseplate']['attributes']['system']['region']['name']
            print('Car Number : '  + numberOfvehicle)
            print('region : ' + regionofVehicle )

#    makeOfvehicle = 'Audi'
 #   modelOfVehicle = 'Q7'
  #  typeOfVehicle = 'SUV'
   # numberOfvehicle = ''
    #regionofVehicle = ''
    #colorOfVehicle = 'Red'
    #numberPlateFound = 0

    img_128 = prepare_img_128(img_path)
#    with graph.as_default():
#        DamgeDetection_model = load_model(str(modelpath) + '/car_damage-model_retrained.h5')
#        print ("DamgeDetection_model loaded")
    g2 = car_damage_gate(img_128, DamgeDetection_model)
    print(g2)
    if g2 is False:
        result = {'gate1': 'Car validation check: ', 
        'gate1_result': 1, 
        'gate1_message': {0: None, 1: None},
        'gate2': 'Damage presence check: ',
        'gate2_result': 0,
       'makeModelGate' : numberPlateFound ,
        'gate2_message': {0: 'Are you sure that your car is damaged? Please retry your submission.'},
        'location': None,
        'severity': None,
        'make': makeOfvehicle ,
        'model' : modelOfVehicle , 
        'color' : colorOfVehicle ,
        'typeOfvehicle' : typeOfVehicle,
        'numberplate' : numberOfvehicle ,
        'region' : regionofVehicle ,
        'final': 'Damage assessment unsuccessful!'}
        return result

#    img_128 = prepare_img_128(img_path)
#    with graph.as_default():
#        location_model =  load_model(str(modelpath) + '/carLocationWithfrontAndBack3400Images.h5')
#        print ("Location model loaded")
#        severity_model = load_model(str(modelpath)+ '/car_damage_severity.h5')
#        print ("Severity model loaded")

    g3 = location_assessment(img_128, location_model)
    print("Location of damage : " + g3)
    img_256 = prepare_img_256(img_path)
    g4 = severity_assessment(img_256, severity_model)
    print ('Severity of damage : ' + g4)

    print(userid)
    customer_ID = 1001
    print(customer_ID)
    import psycopg2
    conn = psycopg2.connect(database="TouchNpaid", user = "postgres", password = "Admin123", host = "10.109.32.131", port = "5454")
    cur = conn.cursor()
    query = " SELECT  YOM , PRICE from POLICYINFO WHERE USERID = '{c}'".format(c = customer_ID)
    cur.execute(query)
    rows = cur.fetchall()
#    print ("USERID = ", rows[0][0])
#    print ("POLICYID = ", rows[0][1])
#    print ("VEHICLENUM = ", rows[0][2])
#    print ("MAKE = ", rows[0][3])
#    print ("MODEL = ", rows[0][4] )
    yearOfMan =  int(rows[0][0])
    print("Manufacturing Year: " + str(yearOfMan))
    costOfCar = int(rows[0][1] )
    print("Cost of car : $" + str(costOfCar))
    conn.close()

    depreCost = 5
    currentYr = 2019
    deductible = 250
    segmentPercent = 0.125

    percentDepre = (currentYr - yearOfMan) * depreCost
    print('percentDepre : ' + str(percentDepre))
    finalAfterDepre =  ((100 - percentDepre) / 100 ) * costOfCar
    print('finalAfter depreciation : ' + str(finalAfterDepre))
    estimatedCost = 0
    severitycheck = str(g4)

    if 'Severe' in severitycheck:
        print('sever loop')
        estimatedCost = finalAfterDepre*segmentPercent
        estimatedCost = estimatedCost - deductible
    elif 'Moderate' in severitycheck :
        print('moderate loop')
        estimatedCost = finalAfterDepre*segmentPercent*0.66
        estimatedCost = estimatedCost - deductible
    else:
        estimatedCost = finalAfterDepre*segmentPercent*0.33
        estimatedCost = estimatedCost - deductible
    print(estimatedCost)

    result = {'gate1': 'Car validation check: ', 
    'gate1_result': 1, 
    'gate1_message': {0: None, 1: None},
    'gate2': 'Damage presence check: ',
    'gate2_result': 1,
    'gate2_message': {0: None, 1: None},
    'location': g3,
    'severity': g4,
    'modelGate' : numberPlateFound ,
    'make': makeOfvehicle ,
    'model' : modelOfVehicle ,
    'color' : colorOfVehicle ,
    'typeOfvehicle' : typeOfVehicle,
    'numberplate' : numberOfvehicle ,
    'region' : regionofVehicle ,
    'estimatedcost' : '$ ' + str(estimatedCost) ,
    'final': 'Damage assessment complete!'}
    return result

0 个答案:

没有答案