name unicode not defined python3 - pyqt4

i have been trying to run this code
this is the error
File "C:/hari/Academics/python/py programs/gui qt4/book/calculator.py", line 27, in updateUi
text = unicode(self.lineedit.text(),'utf-8')
NameError: name 'unicode' is not defined
the code :
from __future__ import division
from math import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
class Form(QDialog):
def __init__(self,parent =None):
super(Form,self).__init__(parent)
self.browser =QTextBrowser()
self.lineedit =QLineEdit("type an exp")
self.lineedit.selectAll()
layout=QVBoxLayout()
layout.addWidget(self.browser)
layout.addWidget(self.lineedit)
self.setLayout(layout)
self.lineedit.setFocus()
self.connect(self.lineedit, SIGNAL("returnPressed()"), self.updateUi)
self.setWindowTitle("Calculate")
def updateUi(self):
try:
text = unicode(self.lineedit.text())
print(type(text))
self.browser.append(text+" = <b>"+eval(text)+"</b>" )
except:
self.browser.append("<font color=red>"+ text + " is invalid</font>")
app=QApplication(sys.argv)
f=Form()
f.show()
app.exec_()

in python 3 strings are unicode by default.
Remove the unicode function, replace by str.
https://docs.python.org/3.0/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit
There's also a little recipe to make the code python 2 & 3 compatible:
try:
unicode # check if unicode is defined
except NameError: # not found: python 3: replace by str
unicode = str
Like Bakuriu said in his comment, never use a bare except:
Prefer:
except Exception as e:
print("Problem "+repr(e))
# the line below requires some HTML normalization or resulting
# html could be incorrect
import re
ne = re.sub("[^\w]"," ",str(e))
self.browser.append("<font color=red>"+ne+"</font>")
Now you have the real/next exception displayed.

Hope you are using Python 3 , so please replace
Unicode function with String Str function.
def updateUi(self):
try:
text = str(self.lineedit.text()) ##replaced here

Related

What is the SyntaxError in the a "def" line in a python script?

I am trying to run the follow python script:
#!/usr/bin/env python
#Author Jared Adolf-Bryfogle
#Python Imports
import os
import sys
from pathlib import Path
from typing import Union
#Append Python Path
p = os.path.split(os.path.abspath(__file__))[0]+"/src"
sys.path.append(p) #Allows all modules to use all other modules, without needing to update pythonpath
#Project Imports
from pic2.modules.chains.ProposedIgChain import ProposedIgChain
from pic2.modules.chains.IgChainSet import IgChainSet
from pic2.modules.chains.IgChainFactory import IgChainFactory
from pic2.modules.chains.AbChainFactory import AbChainFactory
from pic2.tools.fasta import *
class IgClassifyFASTA:
"""
Identify CDRs from a Fasta File
"""
def __init__(self, fasta_path: Union[Path, str]):
self.fasta_path = str(fasta_path)
self.outdir = os.getcwd()
self.outname = "classified"
self.fasta_paths = split_fasta_from_fasta(os.path.abspath(self.fasta_path), "user_fasta_split_"+self.outname, self.outdir)
def __exit__(self):
for path in self.fasta_paths:
if os.path.exists(path):
os.remove(path)
def set_output_path(self, outdir: Union[Path, str]):
self.outdir = str(outdir)
def set_output_name(self, outname: Union[Path, str]):
self.outname = str(outname)
My python version is 3.8, and the pic2 is a conda env. I get the the following error:
File "IgClassifyFASTA.py", line 29
def __init__(self, fasta_path:Union[Path, str]):
SyntaxError: invalid syntax
I cannot figure out what's wrong with this line. Could you kindly give me some hint what's the wrong lying in? I will appreciate any help.
Best regards!

Python ConfigParser.write() missing 1 required positional argument 'fp'?

Code here (left out the unrelated Kivy stuff):
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.widget import Widget
from configparser import ConfigParser
import os
class MIDIApp(App):
def build(self):
self.config = ConfigParser()
self.config.read('values.ini')
Window.size = Window.size
return MainWindow()
def input1_comp_move(self, value):
print(int(value))
def input1_save_comp_value(self, value):
self.config['Input1']['comp'] = str(value)
print(str(value))
with open('values.ini', 'w') as config_file:
ConfigParser.write(config_file)
print('Input1 comp value is ', value)
class MainWindow(Widget):
pass
if __name__ == '__main__':
MIDIApp().run()
When I run this I get the error ConfigParser.write(self.config_file)
TypeError: write() missing 1 required positional argument: 'fp'
And when I debug by leaving it blank it requires 2 positional arguments 'self' and 'filename', it didn't require that when I tried to used this another program. What am I missing?
It should be self.config.write(self.config_file) or, if you insist, ConfigParser.write(self.config, self.config_file).
Thanks ForceBru

solve:AttributeError: module 'tensorflow' has no attribute 'app'

I got an error when I use the code in cmd by using the code:
python generate_tfrecord.py --csv_input=images\train_labels.csv --image_dir=images\train --output_path=train.record""
Usage:
# From tensorflow/models/
# Create train data:
python generate_tfrecord.py --csv_input=data/train_labels.csv --output_path=train.record
# Create test data:
python generate_tfrecord.py --csv_input=data/test_labels.csv --output_path=test.record
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import os
import io
import pandas as pd
import tensorflow as tf
from PIL import Image
from object_detection.utils import dataset_util
from collections import namedtuple, OrderedDict
flags = tf.compat.v1.flags
flags.DEFINE_string('csv_input', '', 'Path to the CSV input')
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
flags.DEFINE_string('image_dir', '', 'Path to images')
FLAGS = flags.FLAGS
# TO-DO replace this with label map
def class_text_to_int(row_label):
if row_label == 'put your selected items':
return 1
else:
None
def split(df, group):
data = namedtuple('data', ['filename', 'object'])
gb = df.groupby(group)
return [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]
def create_tf_example(group, path):
with tf.gfile.GFile(os.path.join(path, '{}'.format(group.filename)), 'rb') as fid:
encoded_jpg = fid.read()
encoded_jpg_io = io.BytesIO(encoded_jpg)
image = Image.open(encoded_jpg_io)
width, height = image.size
filename = group.filename.encode('utf8')
image_format = b'jpg'
xmins = []
xmaxs = []
ymins = []
ymaxs = []
classes_text = []
classes = []
for index, row in group.object.iterrows():
xmins.append(row['xmin'] / width)
xmaxs.append(row['xmax'] / width)
ymins.append(row['ymin'] / height)
ymaxs.append(row['ymax'] / height)
classes_text.append(row['class'].encode('utf8'))
classes.append(class_text_to_int(row['class']))
tf_example = tf.train.Example(features=tf.train.Features(feature={
'image/height': dataset_util.int64_feature(height),
'image/width': dataset_util.int64_feature(width),
'image/filename': dataset_util.bytes_feature(filename),'image/source_id': dataset_util.bytes_feature(filename),
'image/encoded': dataset_util.bytes_feature(encoded_jpg),
'image/format': dataset_util.bytes_feature(image_format),
'image/object/bbox/xmin': dataset_util.float_list_feature(xmins)'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),
'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),
'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
'image/object/class/label': dataset_util.int64_list_feature(classes),
}))
return tf_example
def main(_):
writer = tf.python_io.TFRecordWriter(FLAGS.output_path)
path = os.path.join(FLAGS.image_dir)
examples = pd.read_csv(FLAGS.csv_input)
grouped = split(examples, 'filename')
for group in grouped:
tf_example = create_tf_example(group, path)
writer.write(tf_example.SerializeToString())
writer.close()
output_path = os.path.join(os.getcwd(), FLAGS.output_path)
print('Successfully created the TFRecords: {}'.format(output_path))
if __name__ == '__main__':
tf.app.run()
tf.app.run()
The error message got was:
Traceback (most recent call last): File "generate_tfrecord.py", line
102, in
tf.app.run()
AttributeError: module 'tensorflow' has no attribute 'app'
Can any one help me?
If you're using TensorFlow v2, app.run has been moved to tf.compat.v1.app.run, as shown here.
If you downgrade your tensorflow to other version i.e 1.x.
It should work fine then.
Do that by using the command pip install tensorflow==1.7.0
just try replacing import tensorflow as tf with import tensorflow.compat.v1 as tf and nothing else, i was facing the same issue .This worked for me.
use abseil if you don't want to downgrade
from absl import app
if __name__ == '__main__':
app.run(main)

python3 OSError: [Errno -9999] Unanticipated host error with pyaudio in speech recognition AI

I am working on an AI, like Jarvis in python3. I am using the python speech_recognition module and pyaudio and everything else required acording to this page.
https://pypi.python.org/pypi/SpeechRecognition/
I have it on a raspberry pi now, before i was using my mac which was working fine. Now sometimes i get an error when running my Jarvis code on my Raspberry pi! Not always but frequetly enough to put a wrench in our progress. And not knowing when the error will come is a big problem and we need to get rid of it. Iḿ using a blue Snowball mic. Here is my code and my error if you could help, that would be great thanks!
Traceback (most recent call last):
File "/media/pi/TRAVELDRIVE/Jarvis(10.0).py", line 172, in <module>
with m as source: r.adjust_for_ambient_noise(source)
File "/usr/local/lib/python3.4/dist-packages/speech_recognition/__init__.py", line 140, in __enter__
input=True, # stream is an input stream
File "/usr/local/lib/python3.4/dist-packages/pyaudio.py", line 750, in open
stream = Stream(self, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/pyaudio.py", line 441, in __init__
self._stream = pa.open(**arguments)
OSError: [Errno -9999] Unanticipated host error
Jarvis.py
#JARVIS mark 10. python 3.5.1 version
#JUST.A.RATHER.VERY.INTELEGENT.SYSTEM.
##import speech_recognition
##import datetime
##import os
##import random
##import datetime
##import webbrowser
##import time
##import calendar
from difflib import SequenceMatcher
import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.tokenize import PunktSentenceTokenizer
import speech_recognition as sr
import sys
from time import sleep
import os
import random
r = sr.Recognizer()
m = sr.Microphone()
#Brain functions, vocab!
what_i_should_call_someone = [""]
Good_Things = ["love","sweet","nice","happy","fun","awesome","great"]
Bad_Things = ["death","kill","hurt","harm","discomfort","rape","pain","sad","depression","depressed","angry","mad","broken","raging","rage"]
# Words that you might says in the beginning of your input, for example: "um hey where are we!?!"
Slang_Words = ["um","uh","hm","eh"]
# Put all greetings in here
Static_Greetings = ["Hey","Hi","Hello"]
# Put your AIs Name and other names just in case.
Name = ["jarvis"]
posible_answer_key_words = ["becuase","yes","no"]
Chance_that_question_was_asked_1 = 0
Chance_that_question_was_asked_2 = 0
certainty_question_was_asked = 0
Me_statment_keywords = ["you","your","yours"]
You_statment_keywords = ["i","i'm","me"]
global certainty_person_is_talking_to_me
what_i_said = ("")
Just_asked_querstion = False
the_last_thing_i_said = ("")
the_last_thing_person_said = ("")
what_person_said = ("")
what_person_said_means = [""]
what_im_about_to_say = [""]
why_im_about_to_say_it = [""]
who_im_talking_to = [""]
how_i_feel = [""]
why_do_i_feel_the_way_i_do = [""]
what_i_am_thinking = ("")
# ways to describe the nouns last said
it_pronouns = ["it","they","she","he"]
# last person place or thing described spoken or descussed!
last_nouns = [""]
# Sample of random questions so Jarvis has somthing to index to know what a question is!
Sample_Questions = ["what is the weather like","where are we today","why did you do that","where is the dog","when are we going to leave","why do you hate me","what is the Answer to question 8",
"what is a dinosour","what do i do in an hour","why do we have to leave at 6.00", "When is the apointment","where did you go","why did you do that","how did he win","why won’t you help me",
"when did he find you","how do you get it","who does all the shipping","where do you buy stuff","why don’t you just find it in the target","why don't you buy stuff at target","where did you say it was",
"when did he grab the phone","what happened at seven am","did you take my phone","do you like me","do you know what happened yesterday","did it break when it dropped","does it hurt everyday",
"does the car break down often","can you drive me home","where did you find me"
"can it fly from here to target","could you find it for me"]
Sample_Greetings = ["hey","hello","hi","hey there","hi there","hello there","hey jarvis","hey dude"]
Question_Keyword_Answer = []
Int_Question_Keywords_In_Input = []
Possible_Question_Key_Words = ["whats","what","where","when","why","isn't","whats","who","should","would","could","can","do","does","can","can","did"]
Possible_Greeting_Key_Words = ["hey","hi","hello",Name]
# In this function: Analyze the user input find out if it's (Question, Answer, Command. Etc) and what is being: Asked, Commanded, ETC.
def Analyze():
def Analyze_For_Greeting():
def Greeting_Keyword_Check():
global Possible_Greeting_Key_Words
Int_Greeting_Keywords_In_Input = []
for words in what_person_said_l_wt:
if words in Possible_Greeting_Key_Words:
Int_Greeting_Keywords_In_Input.append(words)
Amount_Greeting_Keywords = (len(Int_Greeting_Keywords_In_Input))
if Amount_Greeting_Keywords > 0:
return True
def Greeting_Sentence_Match():
for Ran_Greeting in Sample_Greetings:
Greeting_Matcher = SequenceMatcher(None, Ran_Greeting, what_person_said_l).ratio()
if Greeting_Matcher > 0.5:
print (Greeting_Matcher)
print ("Similar to Greeting: "+Ran_Greeting)
return True
Greeting_Keyword_Check()
Greeting_Sentence_Match()
#In this function: determin if the input is a question or not.
def Analyze_For_Question():
# In this function: if there is atleast one question keyword in the user input then return true.
def Question_Keyword_Check():
global Possible_Question_Key_Words
Int_Question_Keywords_In_Input = []
for words in what_person_said_l_wt:
if words in Possible_Question_Key_Words:
Int_Question_Keywords_In_Input.append(words)
Amount_Question_keywords = (len(Int_Question_Keywords_In_Input))
if Amount_Question_keywords > 0:
return True
# In this function: if the users input is simular to other sample questions, return true.
def Question_Sentence_Match():
for Ran_Question in Sample_Questions:
Question_Matcher = SequenceMatcher(None, Ran_Question, what_person_said_l).ratio()
if Question_Matcher > 0.5:
print (Question_Matcher)
print ("Similar to Question: "+Ran_Question)
return True
# In this function: if the first word of the users input is a question keyword and there is a different question keyword in the input return true.
def Question_Verb_Noun_Check():
#if you say "hey jarvis" before somthing like a question or command it will still understand
try:
for word in what_person_said_l_wt:
if word in Static_Greetings or word in Name:
print (word)
Minus_Begin_Greet1 = what_person_said_l_wt.remove(word)
print (Minus_Begin_Greet1)
return True
except IndexError:
pass
Question_Keyword_Check()
Question_Sentence_Match()
Question_Verb_Noun_Check()
if Question_Keyword_Check()==True and Question_Sentence_Match()==True and Question_Verb_Noun_Check()==True:
return True
else:
return False
# All the funtions in Analyze
Analyze_For_Greeting()
Analyze_For_Question()
Conversation=True
Conversation_Started=False
while Conversation==True:
try:
if Conversation_Started==False:
#Greeting()
Conversation_Started=True
with m as source: r.adjust_for_ambient_noise(source)
print(format(r.energy_threshold))
print("Say something!") # just here for now and testing porposes so we know whats happening
with m as source: audio = r.listen(source)
print("Got it! Now to recognize it...")
try:
# recognize speech using Google Speech Recognition
value = r.recognize_google(audio)
# we need some special handling here to correctly print unicode characters to standard output
if str is bytes: # this version of Python uses bytes for strings (Python 2)
print(u"You said {}".format(value).encode("utf-8"))
else: # this version of Python uses unicode for strings (Python 3+)
print("You said {}".format(value))
what_person_said_l = value.lower()
what_person_said_l_wt = word_tokenize(what_person_said_l)
Analyze()
except sr.UnknownValueError:
print ("what was that?")
except sr.RequestError as e:
print("Uh oh! Sorry sir Couldn't request results from Google Speech Recognition service; {0}".format(e))
except KeyboardInterrupt:
pass

Invalid syntax when trying to add patch_http_response_read patch

Hello i'm trying to patch my python code with http://bobrochel.blogspot.com/2010/11/bad-servers-chunked-encoding-and.html but when adding this snippet anywhere in the code I always get invalid syntax. What am I doing wrong?
The start of my code looks like this:
import logging
import argparse
import sys
from arbitrer import Arbitrer
def patch_http_response_read(func):
def inner(*args):
try:
return func(*args)
except httplib.IncompleteRead, e:
return e.partial
return inner
httplib.HTTPResponse.read = patch_http_response_read(httplib.HTTPResponse.read)
class ArbitrerCLI:
def __init__(self):
except doesn't work that way anymore.
except httplib.IncompleteRead as e:
Indent correctly.
The try statement changed in Python 3.x.
import httplib
import logging
import argparse
import sys
from arbitrer import Arbitrer
def patch_http_response_read(func):
def inner(*args):
try:
return func(*args)
except httplib.IncompleteRead as e:
return e.partial
return inner
httplib.HTTPResponse.read = patch_http_response_read(httplib.HTTPResponse.read)
class ArbitrerCLI:
def __init__(self):
...

Resources