pyinstaller and loading pickle file - python-3.x

Has anyone worked with pyinstaller to create windows executables from python scripts? I'm trying to create an executable that loads a pickle file but not successful.
import pickle
filename='test.sav'
try:
model = pickle.load(open(filename, 'rb'))
print('model loaded')
except:
print('An error occurred.')
When run with python 3, it works and loads the model correctly but when run with the executable created by pyinstaller, it will through an exception. Help appreciated.

Im using kivy with pickle and it works correctly.
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.config import Config
import pickle
FRAMES_PER_SECOND = 60.0
Config.set('graphics','multisamples',2)
a = []
class Display(BoxLayout):
def save(self,text):
with open('db.prz','wb') as file:
pickle.dump(text,file)
def loads(self):
with open('db.prz','rb') as file:
a = pickle.load(file)
print(a)
class TestApp(App):
def build(self):
a = Display()
return a
if __name__ == '__main__':
TestApp().run()
kv file:
<Display>:
BoxLayout:
orientation: 'vertical'
TextInput:
id: kvtext
size_hint_y : 0.2
BoxLayout:
orientation : 'horizontal'
Button:
text: 'Save'
on_press: root.save(kvtext.text)
Button:
text: 'Load'
on_press: root.loads()
Spec File Changes:
# -*- mode: python ; coding: utf-8 -*-
from kivy_deps import sdl2, glew
a = Analysis(
datas=[('C:\\Users\\mnt\\Documents\\build_test\\test.kv','.')],
coll = COLLECT(
*[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)],
Note that im not adding my file 'db.prze' to data in Analysis()
I also installed pyi from github not from pip.
If you are loading class object, import its class from file.

Related

cannot import name 'MDToolbar' from 'kivymd.uix.toolbar'

I am trying to run the below code,
from kivymd.uix.screen import MDScreen
from kivymd.app import MDApp
from kivy.uix.image import Image
from kivymd.uix.button import MDFillRoundFlatIconButton, MDFillRoundFlatButton
from kivymd.uix.textfield import MDTextField
from kivymd.uix.label import MDLabel
from kivymd.uix.toolbar import MDToolbar
class ConverterApp(MDApp):
def build(self):
screen = MDScreen()
self.toolbar = MDToolbar(title = 'Binary to Decimal')
self.toolbar.pos_hint = {'top':1}
screen.add_widget(self.toolbar)
return screen
if __name__ == '__main__':
ConverterApp().run()
But seeing a output error, which is
from kivymd.uix.toolbar import MDToolbar
ImportError: cannot import name 'MDToolbar' from 'kivymd.uix.toolbar'
I even searched on google, regarding this module error, but didn't get the required answer.
Can anyone solve this issue?

kivyMD HotReloadViewer error: NoneType' object has no attribute 'fbind'

I am trying to run the kivyMD HotReloadViewer script and when I run this code I get an error message inside the HotReloadViewer widget that says: 'NoneType' object has no attribute 'fbind'. I have researched the error and it is explained that somewhere in the code a variable is not defined or a function is returning None. I am wondering if there is something I am missing here, or advice on debugging where undefined variable or function is located. I am running kivymd-0.104.2.dev0 and have watchdog installed.
from kivy.lang import Builder
from kivymd.app import MDApp
KV = '''
#:import KivyLexer kivy.extras.highlight.KivyLexer
#:import HotReloadViewer kivymd.utils.hot_reload_viewer.HotReloadViewer
BoxLayout:
CodeInput:
lexer: KivyLexer()
style_name: "native"
on_text: app.update_kv_file(self.text)
size_hint_x: .7
HotReloadViewer:
size_hint_x: .3
path: app.path_to_kv_file
errors: True
errors_text_color: 1, 1, 0, 1
errors_background_color: app.theme_cls.bg_dark
'''
class Example(MDApp):
path_to_kv_file = "kv_file.kv"
def build(self):
self.theme_cls.theme_style = "Dark"
return Builder.load_string(KV)
def update_kv_file(self, text):
with open(self.path_to_kv_file, "w") as kv_file:
kv_file.write(text)
Example().run()
class Example(MDApp):
path_to_kv_file = "kv_file.kv" # path to your KV file

Author's code works but mine doesn't [Kivy]

I'm learning from a book about making apps with Kivy and there's this block of code:
from kivy.app import App
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
class TestApp(App):
press_count = 1
def button_press(self, button_pressed):
print('Button Pressed', TestApp.press_count, 'TImes')
TestApp.press_count += 1
def build(self):
my_btn = Button(text='Click Me')
my_btn.bind(on_press=TestApp.button_press)
textinput = TextInput(text='Data Inside TextInput')
box_layout = BoxLayout(orientation='vertical')
box_layout.add_widget(widget=my_btn)
box_layout.add_widget(widget=textinput)
return box_layout
if __name__ == '__main__':
TestApp().run()
when I run this I get understandably TypeError: button_press() missing 1 required positional argument: 'button_pressed' my question is why the author of the book isn't getting this error and the code runs ?
my_btn.bind(on_press=TestApp.button_press)
This is wrong, it should be my_btn.bind(on_press=self.button_press).

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)

How to read a Kivy.properties.NumericProperty value in my code at a specific point

So basically I have a kivy project in which,I have a layout that I use in many classes,as such..I have made in custom and put it in a separate file so I can just reference it from different parts of my code.
Snippet:
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
Builder.load_string('''
<CustLayout>:
#code here
''')
class CustLayout(BoxLayout):
t_length = NumericProperty(0)
my_len = 0
print(my_len)
def __init__(self, **kwargs):
super(Silvertable,self).__init__(**kwargs)
self.bind(t_length=self.on_t_length)
#This statement is executed after all other prints
print(self.t_length)
def on_t_length(self,instance,length):
#I'd like to get kv file value before the next line
self.my_len = length
print(my_len)
My kiv file:
#:import Silvertable silvertables.Silvertable
#chunk of code
BoxLayout:
Silvertable:
t_length: 5
Here,I DO get the value but unfortunately too late.That is,I get the value after the program has finished.my_len Doesn't change it's still 0
Bind Kivy Properties
The value of my_len is 0 (zero) because the print() functions were executed first before the run() method.
The value of my_len did change from 0 to 5 as per binding on property of t_length.
Please refer to the example and trace for details.
Example
main.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty
from kivy.lang import Builder
Builder.load_string('''
<CustLayout>:
t_length: 5
''')
class CustLayout(BoxLayout):
t_length = NumericProperty(0)
my_len = 0
print("\tCustLayout.class level-start: my_len=", my_len)
def __init__(self, **kwargs):
super(CustLayout,self).__init__(**kwargs)
print("\nCustLayout.__init__:")
self.bind(t_length=self.on_t_length)
#This statement is executed after all other prints
print("\tself.t_length=", self.t_length)
print("\tself.my_len=", self.my_len)
def on_t_length(self, instance, length):
print("\nCustLayout.on_t_length:")
#I'd like to get kv file value before the next line
self.my_len = length
print("\tself.my_len=", self.my_len)
print("\tCustLayout.class level-end: my_len=", my_len)
class TestBindProperty(App):
def build(self):
print("\nTestBindProperty.build:")
return CustLayout()
def on_stop(self):
print("\tTestBindProperty.on_stop: my_len=", self.root.my_len)
if __name__ == "__main__":
TestBindProperty().run()
Output

Resources