How to get rid of this problem in openCV tkinter code - python-3.x

I am working on a facial recognition based attendance system .This is my first project so i am not well acquainted with how to deal with errors. I am stuck in the middle and don't know how to solve the error. My terminal displays the following error:
PS E:\Project Work> & "C:/Users/Naik Faheem/AppData/Local/Programs/
Python/Python39/python.exe" "e:/Project Work/test.py"
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Naik Faheem\AppData\Local\Programs\Python\
Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "e:\Project Work\test.py", line 62, in face_recog
img=recognize(img,clf,facecascade)
File "e:\Project Work\test.py", line 52, in recognize
coord= draw_boundary(img,facecascade,1.1,10,255,"Face",clf)
File "e:\Project Work\test.py", line 39, in draw_boundary
n="+".join(n)
TypeError: can only join an iterable
[ WARN:1] global C:\Users\runneradmin\AppD
I HAVE PUT MY ACTUAL CODE BELOW.This code is intended to read classifier.xml file that stores the trained dataset.
from tkinter import *
from PIL import Image, ImageTk
from tkinter import ttk
from tkinter import messagebox
import mysql.connector
import cv2
class Face_recognition:
def __init__(self,root):
self.root=root
self.root.title('Face Detection')
self.root.geometry('1500x800+0+0')
self.root.config(bg='gray')
title_lbl=Label(self.root,text='FACE RECOGNITION',
font=('times new roman',35,'bold'),bg='gray',fg='darkblue')
title_lbl.place(x=0,y=0,width=1500,height=40)
btn=Button(self.root,command=self.face_recog,text='Detect Face',
font=('times new roman',12,'bold'),bg='red')
btn.place(x=650,y=60,width=200,height=40)
def face_recog(self):
def draw_boundary(img,classifier,scaleFactor,minNeighbors,color,text,clf):
gray_image=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
features = classifier.detectMultiScale(gray_image,scaleFactor,minNeighbors)
coord= []
for (x,y,w,h) in features:
cv2.rectangle(img,(x,y),(x+w,y+h),255,3)
id,predict= clf.predict(gray_image[y:y+h,x:x+w])
confidence= int(100*(1-predict/300))
con= mysql.connector.connect( user='root', host='localhost',
password='',database='stu_details')
cur=con.cursor()
cur.execute("select name from stu_info where name= "+str(id-1))
n=cur.fetchone()
n="+".join(n)
if confidence>70:
cv2.putText(img,f"Name: {n}",(x,y-60),cv2.FONT_HERSHEY_COMPLEX,1,255,2)
else:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,255),4)
cv2.putText(img,"Unknown face",(x,y10),
cv2.FONT_HERSHEY_COMPLEX_SMALL,0.8,(255,255,255),3)
coord=[x,y,w,h]
return coord
def recognize(img,clf,facecascade):
coord= draw_boundary(img,facecascade,1.1,10,255,"Face",clf)
return img
facecascade= cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
clf= cv2.face.LBPHFaceRecognizer_create()
clf.read("classifier.xml")
video_cap=cv2.VideoCapture(0)
while True:
ret,img=video_cap.read()
img=recognize(img,clf,facecascade)
cv2.imshow("Welcome to face recognition",img)
if cv2.waitKey(1)==13:
break
video_cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
root=Tk()
app=Face_recognition(root)
root.mainloop()

Error fixed:
Register the records in an ascending id (e.g 1,2,3....)and this problem gets solved

Change your data type from int to varchar in your data base
to get rid of this error.

Related

RuntimeWarning , RuntimeError (Python Al Chat Bot on Discord Server)

My Aim: Be able to integrate Al Chatbot and Discord
import nltk
nltk.download('punkt')
from nltk.stem.lancaster import LancasterStemmer
stemmer=LancasterStemmer()
import numpy
import tflearn
import tensorflow
import random
import json
import pickle
import nest_asyncio
import asyncio
#---------------------------------------------------------------------------
import discord
import os
with open("intents.json") as file:
data=json.load(file)
print(data['intents'])
try:
with open("data.pickle","rb") as f:
words,labels,training,output=pickle.load(f)
except:
words=[]
labels=[]
docs_x=[]
docs_y=[]
for intent in data['intents']:
for pattern in intent['patterns']:
wrds=nltk.word_tokenize(pattern)
words.extend(wrds)
docs_x.append(wrds)
docs_y.append(intent["tag"])
if intent["tag"] not in labels:
labels.append(intent["tag"])
#remove duplicate
words=[stemmer.stem(w.lower()) for w in words if w != "?"]
words=sorted(list(set(words)))
labels=sorted(labels)
training=[]
output=[]
out_empty=[0 for _ in range(len(labels))]
for x, doc in enumerate(docs_x):
bag=[]
wrds=[stemmer.stem(w) for w in doc]
for w in words:
if w in wrds:
bag.append(1)
else:
bag.append(0)
output_row=out_empty[:]
output_row[labels.index(docs_y[x])]=1
training.append(bag)
output.append(output_row)
training=numpy.array(training)
output=numpy.array(output)
with open("data.pickle","wb") as f:
pickle.dump((words,labels,training,output),f)
tensorflow.compat.v1.reset_default_graph()
net=tflearn.input_data(shape=[None,len(training[0])])
net=tflearn.fully_connected(net,16)
net=tflearn.fully_connected(net,16)
net=tflearn.fully_connected(net,len(output[0]),activation="softmax")
net=tflearn.regression(net)
model=tflearn.DNN(net)
model.fit(training, output,n_epoch=10000,batch_size=16,show_metric=True )
model.save('C:/Users/Desktop/chatbot/model/model.tflearn')
model.load('C:/Users/Desktop/chatbot/model/model.tflearn')
def bag_of_words(s,words):
bag=[0 for _ in range(len(words))]
s_words=nltk.word_tokenize(s)
s_words=[stemmer.stem(word.lower()) for word in s_words]
for se in s_words:
for i,w in enumerate(words):
if w==se:
bag[i]=1
return numpy.array(bag)
def chat():
print("start talking with the bot (type quit to stop!")
while True:
inp=input("You:")
if inp.lower()=="quit":
break
results= model.predict([bag_of_words(inp,words)])[0]
# print("results:",results)
results_index=numpy.argmax(results)
if results[results_index]>0.7:
tag=labels[results_index]
print("tag:", tag)
for tg in data["intents"]:
if tg["tag"]==tag:
responses=tg['responses']
client=discord.Client() #FOR DISCORD--------------------------------------
async def on_message(message):
if inp.author == client.user:
return
if inp.content.startswith("$M-bot"):
response=responses.request(inp.content[7:])
await asyncio.sleep(5)
await inp.channel.send(response)
on_message(inp)
client.run("API KEY TAKEN FROM DISCORD for BOT")
print("Bot:",random.choice(responses))
else:
print("I didn't get that. Please try again")
chat()
Warnings and Errors (Pyconsole):
start talking with the bot (type quit to stop!
You:hello
tag: greeting
C:/Users/Desktop/chatbot/chatbot.py:154: RuntimeWarning: coroutine 'chat.<locals>.on_message' was never awaited
on_message(inp)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
File "F:\Anaconda\lib\site-packages\discord\client.py", line 713, in run
loop.run_forever()
File "F:\Anaconda\lib\asyncio\base_events.py", line 560, in run_forever
self._check_running()
File "F:\Anaconda\lib\asyncio\base_events.py", line 552, in _check_running
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "F:\Anaconda\lib\site-packages\discord\client.py", line 90, in _cleanup_loop
_cancel_tasks(loop)
File "F:\Anaconda\lib\site-packages\discord\client.py", line 75, in _cancel_tasks
loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
File "F:\Anaconda\lib\asyncio\base_events.py", line 592, in run_until_complete
self._check_running()
File "F:\Anaconda\lib\asyncio\base_events.py", line 552, in _check_running
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/Desktop/chatbot/chatbot.py", line 162, in <module>
chat()
File "C:/Users/Desktop/chatbot/chatbot.py", line 155, in chat
client.run("API KEY TAKEN FROM DISCORD for BOT")
File "F:\Anaconda\lib\site-packages\discord\client.py", line 719, in run
_cleanup_loop(loop)
File "F:\Anaconda\lib\site-packages\discord\client.py", line 95, in _cleanup_loop
loop.close()
File "F:\Anaconda\lib\asyncio\selector_events.py", line 89, in close
raise RuntimeError("Cannot close a running event loop")
RuntimeError: Cannot close a running event loop
PROBLEM: Hello Friends, I'm trying to make a chatbot that works on discord and can give its answers through the artificial intelligence model I built, but I am getting a RuntimeWarning: Enable tracemalloc to get the object allocation traceback and RuntimeError: This event loop is already running How can I solve these?
Your error is because you keep reinitiating discord.Client. In every program, there should be only one instance of discord.Client. If you want to make it spit out the last response, you should move client out of the loop. Set the bot's response to a global variable and have the bot spit out the global variable when a command is sent
arrangements:
import nltk
nltk.download('punkt')
from nltk.stem.lancaster import LancasterStemmer
stemmer=LancasterStemmer()
import numpy
import tflearn
import tensorflow
import random
import json
import pickle
import nest_asyncio
import asyncio
#-------------------------------------------------------------------------------
import discord
import os
with open("intents.json") as file:
data=json.load(file)
print(data['intents'])
client=discord.Client() #OUT OF LOOP
#client.event #LISTEN EVENTS
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("$M-bot"):
response=responses.request(message.content[7:])
await message.channel.send(response)
try:
with open("data.pickle","rb") as f:
words,labels,training,output=pickle.load(f)
except:
words=[]
labels=[]
docs_x=[]
docs_y=[]
for intent in data['intents']:
for pattern in intent['patterns']:
wrds=nltk.word_tokenize(pattern)
words.extend(wrds)
docs_x.append(wrds)
docs_y.append(intent["tag"])
if intent["tag"] not in labels:
labels.append(intent["tag"])
#remove duplicate
words=[stemmer.stem(w.lower()) for w in words if w != "?"]
words=sorted(list(set(words)))
labels=sorted(labels)
training=[]
output=[]
out_empty=[0 for _ in range(len(labels))]
for x, doc in enumerate(docs_x):
bag=[]
wrds=[stemmer.stem(w) for w in doc]
for w in words:
if w in wrds:
bag.append(1)
else:
bag.append(0)
output_row=out_empty[:]
output_row[labels.index(docs_y[x])]=1
training.append(bag)
output.append(output_row)
training=numpy.array(training)
output=numpy.array(output)
with open("data.pickle","wb") as f:
pickle.dump((words,labels,training,output),f)
tensorflow.compat.v1.reset_default_graph()
net=tflearn.input_data(shape=[None,len(training[0])])
net=tflearn.fully_connected(net,16)
net=tflearn.fully_connected(net,16)
net=tflearn.fully_connected(net,len(output[0]),activation="softmax")
net=tflearn.regression(net)
model=tflearn.DNN(net)
model.fit(training, output,n_epoch=5000,batch_size=16,show_metric=True )
model.save('C:/Users/Desktop/chatbot/model/model.tflearn')
model.load('C:/Users/Desktop/chatbot/model/model.tflearn')
def bag_of_words(s,words):
bag=[0 for _ in range(len(words))]
s_words=nltk.word_tokenize(s)
s_words=[stemmer.stem(word.lower()) for word in s_words]
for se in s_words:
for i,w in enumerate(words):
if w==se:
bag[i]=1
return numpy.array(bag)
def chat():
global responses #GLOBAL VARIABLES
global inp #GLOBAL VARIABLES
print("start talking with the bot (type quit to stop!")
while True:
inp=input("You:")
if inp.lower()=="quit":
break
results= model.predict([bag_of_words(inp,words)])[0]
# print("results:",results)
results_index=numpy.argmax(results)
if results[results_index]>0.7:
tag=labels[results_index]
print("tag:", tag)
for tg in data["intents"]:
if tg["tag"]==tag:
responses=tg['responses']
print("Bot:",random.choice(responses))
else:
print("I didn't get that. Please try again")
chat()
client.run("API KEY")

Weird illegal tkinter state when calling `widget.destroy` from a `widget.after` script

I was creating a simple program (a label that refreshes itself every 0.1 sec) but I ran into a problem. This is my code:
import tkinter as tk
def loop():
global label
# If the label exists, destroy it
if label is not None:
label.destroy()
# Create a label
label = tk.Label(root)
label.pack() # You don't even need this line for the error
# After some time call `loop` again
label.after(100, loop)
label = None
root = tk.Tk()
# Start the loop
loop()
root.mainloop()
The error traceback shows:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Program Files\Python37\lib\tkinter\__init__.py", line 752, in callit
self.deletecommand(name)
File "C:\Program Files\Python37\lib\tkinter\__init__.py", line 601, in deletecommand
self._tclCommands.remove(name)
AttributeError: 'NoneType' object has no attribute 'remove'
When I changed label.after(...), into root.after(...) it worked. My guess is that tkinter goes in an illegal state after I call label.destroy() from the label.after(...) script. I don't know if the problem comes from tkinter or _tkinter.
Can anyone prove that that's causing problem or suggest another explanation?
PS: Python 3.7.9
I don't know how or what or why is the problem but I think I fixed it (it doesn't throw an error at least) maybe it happens because the widget gets destroyed while it has the .after still affecting it or sth like that:
import tkinter as tk
def loop():
global label
# If the label exists, destroy it
if label:
label.after(0, label.destroy)
# Create a label
label = tk.Label(root)
label.pack() # You don't even need this line for the error
# After some time call `loop` again
label.after(100, loop)
label = None
root = tk.Tk()
# Start the loop
loop()
root.mainloop()
Another thing is that it manages to do exactly 2 full loops before throwing an error

Resize image in Tkinter

So, I need to resize an image in tkinter. Before you do anything - this is not a duplicate. I have gone through every other question on this site and none have helped me. The thing with me is - I don't wan't to save the image. I need to load the image, resize it, then display it with PhotoImage in a label. I tried to use ImageTk, but for some reason it won't work.
Here's my code with ImageTk:
from tkinter import *
import PIL
from PIL import Image, ImageTk
root = Tk()
left_nose_path_white = Image.open(r'C:\Users\User\Documents\Python stuff\Other apps\Veteris\Dog photos\Advanced\Sides\GIF\Nose\Nose (left) - White.gif')
def resize_image():
global left_nose_path_white
total_screen_width = root.winfo_screenwidth()
total_screen_height = root.winfo_screenheight()
frame_width, frame_height = left_nose_path_white.size
dog_new_width = int(frame_width / 3)
dog_new_height = int(frame_height / 3)
left_nose_path_white = left_nose_path_white.resize((dog_new_width, dog_new_height), Image.LANCZOS)
resize_image()
left_nose_img_white = ImageTk.PhotoImage(file = left_nose_path_white)
label = Label(image = left_nose_img_white)
label.pack()
root.mainloop()
This returns the error:
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 124, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
My code should find the width and height of the original image, divide it by 3, and then show it. The reason I don't want to have to save the image is because the user will open the application several times.
I'm new to using PILL/Pillow, so the answer may be obvious.
I have Pillow installed using pip.
I only have one version of Python on my computer (Python 3.7)
Full Error:
Traceback (most recent call last):
File "C:\Users\User\Documents\Python stuff\Other apps\Veteris\Scripts\Veteris_program.py", line 230, in <module>
left_nose_img_white = ImageTk.PhotoImage(file = left_nose_path_white)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 95, in __init__
image = _get_image_from_kw(kw)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 64, in _get_image_from_kw
return Image.open(source)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 2779, in open
prefix = fp.read(16)
AttributeError: 'Image' object has no attribute 'read'
Exception ignored in: <function PhotoImage.__del__ at 0x000002B0A8A49950>
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 124, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
Thanks for the help!

ImportError: cannot import name 'itemgetter' from 'operator'

Help me with my problem, I've made some file that named 'percobaan.py' and I ran it with cmd and it's got some error. the error say ImportError: cannot import name 'itemgetter' from 'operator', But if I run my code in python IDLE the code runs without any errors.
My code:
import tkinter
def msg():
print("i'm learning tkinter built in")
root = tkinter.Tk()
label = tkinter.Label(root, text='welcome to the tkinter built in project')
label.pack()
label2 = tkinter.Label(root,text='choose your favorite programming languange',
justify=tkinter.CENTER,
padx=20)
label2.pack()
tkinter.Radiobutton(root, text='python',padx=20, value= 1).pack(anchor=tkinter.N)
tkinter.Radiobutton(root, text='Javascript',padx=20, value= 2).pack(anchor=tkinter.N)
tkinter.Radiobutton(root, text='C++',padx=20, value= 3).pack(anchor=tkinter.N)
tkinter.Radiobutton(root, text='C',padx=20, value= 4).pack(anchor=tkinter.N)
frame = tkinter.Frame(root)
frame.pack()
button = tkinter.Button(frame, text='quit',fg='black',command=quit)
button.pack(side=tkinter.LEFT)
slogan = tkinter.Button(frame, text='see the message',command=msg)
slogan.pack(side=tkinter.RIGHT)
root.mainloop()
and the error says:
Traceback (most recent call last):
File "GUI.py", line 1, in <module>
import tkinter
File "C:\Users\khairunnisa\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 39, in <module>
import re
File "C:\Users\khairunnisa\AppData\Local\Programs\Python\Python37-32\lib\re.py", line 125, in <module>
import functools
File "C:\Users\khairunnisa\AppData\Local\Programs\Python\Python37-32\lib\functools.py", line 21, in <module>
from collections import namedtuple
File "C:\Users\khairunnisa\AppData\Local\Programs\Python\Python37-32\lib\collections\__init__.py", line 21, in <module>
from operator import itemgetter as _itemgetter, eq as _eq
ImportError: cannot import name 'itemgetter' from 'operator' (D:\JOB\__python\exercise_oop\GUI\operator.py)
I've tried many times to run this code and the packages are already installed on my PC, but the result is still nothing.
any idea why?

pycharm project works on 'run' but pyinstaller --onefile gives errors related to pulp

I've been working on a project where a user can upload a file for analysis via pulp. When I run the project in pycharm it works fine, but after I build a --onefile with pyinstaller... I get the following traceback
Exception in Tkinter callback
Traceback (most recent call last):
File "tkinter\__init__.py", line 1702, in __call__
File "example.py", line 29, in get_file
File "pydfs_lineup_optimizer\lineup_optimizer.py", line 351, in optimize
File "pydfs_lineup_optimizer\solvers\pulp_solver.py", line 39, in solve
File "site-packages\pulp\pulp.py", line 1664, in solve
AttributeError: 'NoneType' object has no attribute 'actualSolve'
Here is a piece of the code I'm having an issue with:
import tkinter as tk
from tkinter import *
from tkinter import filedialog
from tkinter.filedialog import askopenfilename
import csv
import time
import os, sys
import PIL
from PIL import Image, ImageTk
from tkinter.font import Font
def get_file():
global file
file = tk.filedialog.askopenfilename()
def run_it():
from pydfs_lineup_optimizer import Site, Sport, get_optimizer
optimizer = get_optimizer(Site.FANDUEL, Sport.BASEBALL)
optimizer.load_players_from_CSV(file)
lineup_generator = optimizer.optimize(3)
with open('Lineup.csv', "w") as csv_file:
writer = csv.writer(csv_file, delimiter=' ')
for lineup in lineup_generator:
writer.writerow([lineup])
top = tk.Tk()
top.geometry("600x337")
if getattr(sys, 'frozen', False):
baseDir = sys._MEIPASS
else:
baseDir = os.path.abspath(os.path.dirname(__file__))
image = Image.open(os.path.join(baseDir, 'baseball.jpg'))
photo = ImageTk.PhotoImage(image)
L0 = Label(top, image=photo)
L2 = Button(top, text="UPLOAD", fg="blue", font=font2, command=get_file).grid(row=1, column=4)
L3 = Button(top, text="RUN", fg="blue", font=font2, command=run_it).grid(row=2, column=4)
top.mainloop()
Pulp requires the cbc.exe file to be available to use to actually solve the lp problems.
Unfortunately pyinstaller doesn't pick that up by default and you need to figure out a way to package the cbc.ex file then tell the COIN_CMD() solver where to find it.
Do this by using COIN_CMD(path=<your_path_here>)

Resources