NameError: name 'tf' is not defined
See original GitHub issueHi,
I am trying to make a REST api on python where i put some AI models to predict, so i have to load the using tensorflow. I want to add some workers, so that i can call the server multiple times asynchronously.
I run the script and i get the error that tf name is not defined. I have that moduled imported as import tensorflow as tf but it seems that doesn’t reconigze it.
Does someone know what’s the problem? Thanks!
Below my code:
import uvicorn
from fastapi import FastAPI, Request ,Depends
import cv2
import uvicorn
from fastapi import FastAPI, Request ,Depends
import cv2
import io
from time import sleep
import PIL.Image as Image
import numpy as np
import base64
import tensorflow as tf
import nest_asyncio
import concurrent.futures
from concurrent.futures import ThreadPoolExecutor
import multiprocessing
import binascii
import json
from pathlib import Path
app = FastAPI()
nest_asyncio.apply()
CATEGORIES = ['neg', 'pos']
executor = ThreadPoolExecutor(5)
futures=[]
pred=[]
LIMIT=100
with open('DenseNet169/DenseNet169_model_architecture_contodo2.json', 'r') as f:
DenseNetModel = tf.keras.models.model_from_json(f.read())
DenseNetModel.load_weights('DenseNet169/DenseNet169_model_weights_contodo2.h5')
print("DENSENET")
with open('MobileNet/MobileNet_model_architecture_contodo2.json', 'r') as f:
MobileNetModel = tf.keras.models.model_from_json(f.read())
MobileNetModel.load_weights('MobileNet/MobileNet_model_weights_contodo2.h5')
print("MOBILENET")
with open('Xception/Xception_model_architecture_contodo3.json', 'r') as f:
SqueezeNetModel = tf.keras.models.model_from_json(f.read())
SqueezeNetModel.load_weights('Xception/Xception_model_weights_contodo3.h5')
print("SQUEEZE")
with open('Xception_model_architecture_contodo2.json', 'r') as f:
XceptionModel = tf.keras.models.model_from_json(f.read())
XceptionModel.load_weights('Xception/Xception_model_weights_contodo2.h5')
print("XCEPTION")
with open('InceptionResNetV2/InceptionResNetV2_model_architecture_contodo2.json', 'r') as f:
InceptionResNetModel = tf.keras.models.model_from_json(f.read())
InceptionResNetModel.load_weights('InceptionResNetV2/InceptionResNetV2_model_weights_contodo2.h5')
@app.get('/')
def index():
return {'message': 'Hello, stranger'}
@app.post('/transform')
async def get_name(request: Request):
img = await request.json()
img = img["bytes"]
img = base64.b64decode(img)
nparr = np.fromstring(img, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
lab= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
l, a, b = cv2.split(img)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(4,4))
cl = clahe.apply(l)
limg = cv2.merge((cl,a,b))
gray = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
gray = cv2.cvtColor(gray, cv2.COLOR_BGR2GRAY)
# threshold
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
hh, ww = thresh.shape
# make bottom 2 rows black where they are white the full width of the image
thresh[hh-3:hh, 0:ww] = 0
# get bounds of white pixels
white = np.where(thresh>=200)
xmin, ymin, xmax, ymax = np.min(white[1]), np.min(white[0]), np.max(white[1]), np.max(white[0])
if (xmax - xmin) > LIMIT and (ymax-ymin) > LIMIT:
# crop the image at the bounds adding back the two blackened rows at the bottom
crop = gray[ymin:ymax+3, xmin:xmax]
dim = (224, 224)
resized = cv2.resize(crop, dim, interpolation = cv2.INTER_AREA)
else:
dim = (224, 224)
resized = cv2.resize(crop, dim, interpolation = cv2.INTER_AREA)
lists = resized.tolist()
ret = json.dumps(lists)
return ret
def votePredict(pred):
cont=0
emaitza="neg"
for i in range(0,len(pred)):
if pred[i]=="pos":
cont=cont+1
if(cont>2):
emaitza="pos"
return emaitza
def predictImage(img):
sleep(5)
img=img["bytes"]
img=json.loads(img)
img=np.asarray(img)
img=cv2.merge((img,img,img))
img_np=np.float64(img)/255.0
img = img_np.reshape((-1, 224, 224, 3))
futures.append(executor.submit(DenseNetModel.predict, (img)))
futures.append(executor.submit(MobileNetModel.predict, (img)))
futures.append(executor.submit(SqueezeNetModel.predict, (img)))
futures.append(executor.submit(XceptionModel.predict, (img)))
futures.append(executor.submit(InceptionResNetModel.predict, (img)))
for future in concurrent.futures.as_completed(futures):
pred.append(CATEGORIES[np.argmax(future.result())])
aciertos=votePredict(pred)
return aciertos
@app.post('/predict')
async def predict(request:Request):
futures.clear()
pred.clear()
img=await request.json()
return predictImage(img)
if __name__ == '__main__':
uvicorn.run("REST:app", host="127.0.0.1", port=8888 , workers=2)
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:7 (4 by maintainers)
Top Results From Across the Web
'tf' is not defined on load_model() - using lambda
I have a Keras model that I am trying to export and use in a different python code.
Read more >NameError: name 'tf' is not defined · Issue #14 - GitHub
Hi, I have run your jupyter notebook file succesfully. I have then saved nn4_small2 into a .h5 file. I'm now trying to convert...
Read more >NameError: name 'tf' is not defined?? : r/learnpython - Reddit
Tried to run some entry code rank1_tensor = tf.Variable(["test", "ok", "tim"], tf.string) ... NameError: name 'tf' is not defined??
Read more >tf.keras.Sequential | TensorFlow v2.11.0
Sequential groups a linear stack of layers into a tf.keras.Model. ... When using the delayed-build pattern (no input shape specified), you can
Read more >'tf' is not defined on load_model() - using lambda - DevPress
I have a Keras model that I am trying to export and use in a different python code. Here is my code: from...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
probably not uvicorn related but more an issue with sharing stuff between processes, since you use 2 workers, see https://docs.python.org/3/library/multiprocessing.html#sharing-state-between-processes
will close this, happy to reopen if there is something tied to uvicorn that we missed.
The code that gives error:
what i do to run is:
The error I get is:
Technologies involved: