Pyinstaller cannot compile project with sklearn - python-3.x

I'm trying to compile this simple python 3 (pyconda) machine learning project with sklearn and these imports (it's a simple Ridge regression predictor):
from datetime import date
import pandas as pd
import numpy as np
from sklearn.linear_model import Ridge
pd.options.mode.chained_assignment = None
class covidUpdater:
situazione = ""
def getCovidUpdate(self):
url = "https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-andamento-nazionale/dpc-covid19-ita-andamento-nazionale.csv"
ds = pd.read_csv(url)
return ds.tail(self.giorni)
def __init__(self):
pass
def setGiorni(self,giorni):
self.giorni = giorni
self.situazione = self.getCovidUpdate()
def getCampo(self,campo):
return self.situazione[[campo]]
def getMaxLength(self):
ur1l = "https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-andamento-nazionale/dpc-covid19-ita-andamento-nazionale.csv"
ds1 = pd.read_csv(ur1l)
return len(ds1)
def formatTable(self,campo):
giorniPrediction = 1
updater = covidUpdater()
updater.setGiorni(self.giorni)
updaterFuture = covidUpdater()
updaterFuture.setGiorni(self.giorni+giorniPrediction)
datiCampo = updater.getCampo(campo)
datiCampoFuture = updaterFuture.getCampo(campo)
campo_domani = str(campo) + "_domani"
datiCampo[campo_domani] = datiCampoFuture.shift(-giorniPrediction)
datiCampo = datiCampo.head(self.giorni-giorniPrediction)
datiCampo["id"] = range(datiCampo.iloc[:, 0].size)
return datiCampo
def main():
campo = "nuovi_positivi"
updater = covidUpdater()
giorni = int(input("Inserisci numero giorni da usare come dataset> ") or updater.getMaxLength())
updater.setGiorni(giorni)
print("Giorni selezionati: ",giorni)
df = updater.formatTable(campo)
print("Imposto l'algoritmo di predizione")
X = df.iloc[:, 0].values.reshape(-1,1)
Y = df.iloc[:, 1].values.reshape(-1,1)
regr = Ridge(alpha=1.0,normalize=False,tol=0.1,solver="lsqr")
print("Avvio l'algoritmo di predizione")
regr.fit(X,Y)
Y_pred = regr.predict(X)
print("-----------------------------------\n")
print("Giorni in esame: "+ str(giorni)+"\n")
print("Predizione di (" + str(date.today()) + ") : "+ str(regr.predict(np.array([Y[Y.size-1]])))+"\n")
print("fattore R2: "+ str(regr.score(Y,Y_pred))+"\n")
print("-----------------------------------"+"\n")
if __name__ == "__main__":
main()
By using this command:
pyinstaller --noconfirm --onedir --console --hidden-import "sklearn.linear_model.Ridge" "PATH"
I have this log the final error is:
Traceback
Traceback (most recent call last):
File "d:\pyconda\lib\site-packages\auto_py_to_exe\packaging.py", line 131, in package
run_pyinstaller()
File "d:\pyconda\lib\site-packages\PyInstaller\__main__.py", line 114, in run
run_build(pyi_config, spec_file, **vars(args))
File "d:\pyconda\lib\site-packages\PyInstaller\__main__.py", line 65, in run_build
PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
File "d:\pyconda\lib\site-packages\PyInstaller\building\build_main.py", line 720, in main
build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
File "d:\pyconda\lib\site-packages\PyInstaller\building\build_main.py", line 667, in build
exec(code, spec_namespace)
File "C:\Users\Alex\AppData\Local\Temp\tmp854ytoyk\covid2.spec", line 17, in <module>
noarchive=False)
File "d:\pyconda\lib\site-packages\PyInstaller\building\build_main.py", line 242, in __init__
self.__postinit__()
File "d:\pyconda\lib\site-packages\PyInstaller\building\datastruct.py", line 160, in __postinit__
self.assemble()
File "d:\pyconda\lib\site-packages\PyInstaller\building\build_main.py", line 419, in assemble
self.graph.process_post_graph_hooks()
File "d:\pyconda\lib\site-packages\PyInstaller\depend\analysis.py", line 365, in process_post_graph_hooks
module_hook.post_graph()
File "d:\pyconda\lib\site-packages\PyInstaller\depend\imphook.py", line 440, in post_graph
self._load_hook_module()
File "d:\pyconda\lib\site-packages\PyInstaller\depend\imphook.py", line 407, in _load_hook_module
self.hook_module_name, self.hook_filename)
File "d:\pyconda\lib\site-packages\PyInstaller\compat.py", line 588, in importlib_load_source
return mod_loader.load_module()
File "<frozen importlib._bootstrap_external>", line 407, in _check_name_wrapper
File "<frozen importlib._bootstrap_external>", line 907, in load_module
File "<frozen importlib._bootstrap_external>", line 732, in load_module
File "<frozen importlib._bootstrap>", line 265, in _load_module_shim
File "<frozen importlib._bootstrap>", line 696, in _load
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "d:\pyconda\lib\site-packages\_pyinstaller_hooks_contrib\hooks\stdhooks\hook-zmq.py", line 21, in <module>
hiddenimports = ['zmq.utils.garbage'] + collect_submodules('zmq.backend')
File "d:\pyconda\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 595, in collect_submodules
repr(pkg_dir), package))
File "d:\pyconda\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 79, in exec_statement
return __exec_python_cmd(cmd)
File "d:\pyconda\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 68, in __exec_python_cmd
txt = exec_python(*cmd, env=pp_env)
File "d:\pyconda\lib\site-packages\PyInstaller\compat.py", line 521, in exec_python
return exec_command(*cmdargs, **kwargs)
File "d:\pyconda\lib\site-packages\PyInstaller\compat.py", line 316, in exec_command
out = out.decode(encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8a in position 112: invalid start byte
Full log here: https://pastebin.com/XuBeLz3X

I think you should start with the first error in the log:
3560572 INFO: Analyzing hidden import 'sklearn.linear_model.Ridge'
3560576 ERROR: Hidden import 'sklearn.linear_model.Ridge' not found
Have you had a look at this thread with the Hidden import error? How do you resolve 'hidden imports not found!' warnings in pyinstaller for scipy?
I think you need to adjust your hidden imports, so that 'sklearn.linear_model.Ridge' can be found.
And I just tried running your code in Google Colab (https://colab.research.google.com/) and it works there. Perhaps you can run your code there?

Related

AttributeError: 'PathDistribution' object has no attribute 'name'

I am trying to run a simple workflow using celery and using this documentation. I am using chain to sequentially run the tasks, with following workflow
Extract a file, tokenize it and load JSON dumps of sentence tokens of a doc to another (new)file. Iterate the workflow over list of files in a folder
Following is my code:-
folder structure
celery-pipeline/
├── celeryapp.py
├── celeryconfig.py
├── data/
├── output/
└── tasks.py
celeryapp.py
from celery import Celery
app = Celery()
app.config_from_object('celeryconfig')
celeryconfig.py
imports = ('tasks',)
broker_url = 'redis://localhost:6379/0'
result_backend = 'db+postgresql://celery_user:celery_user#127.0.0.1:5432/celery_db'
task_ignore_result = False
task_track_started = True
task_default_queue = 'default'
task_default_rate_limit = '20/s'
task_time_limit = 7200
worker_pool_restarts = True
tasks.py
import os
import json
import spacy
import logging
from datetime import datetime, timedelta
from celeryapp import app
sp = spacy.load('en_core_web_sm')
#app.task(bind=True)
def extract(self, filename):
file_path = os.path.join(os.getcwd(), 'data', filename)
doc = open(file_path).read()
print('Extract called')
return doc
#app.task(bind=True)
def transform_tokenize_doc(self, doc:str):
sentences = []
for sent in sp(doc).sents:
sentences.append(str(sent).strip())
return sentences
#app.task(bind=True)
def load(self, filename, *args):
with open(os.path.join(os.getcwd(), 'output', filename), 'a+') as file:
file.write(json.dumps(args, indent=4))
if __name__ == '__main__':
tasks = []
for filename in os.listdir(os.path.join(os.getcwd(), 'data'))[:10]:
print(f'filename is {filename}')
etl = (extract.s(filename) | transform_tokenize_doc.s() | load.s(filename)).apply_async()
tasks.append(etl)
for task in tasks:
task.get()
On running celery -A tasks worker --loglevel=info inside root folder - celery-pipeline/, I am getting following error:-
Traceback (most recent call last):
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/kombu/utils/objects.py", line 41, in __get__
return obj.__dict__[self.__name__]
KeyError: 'control'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/ubuntu/Documents/projects/celery-venv/bin/celery", line 8, in <module>
sys.exit(main())
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/__main__.py", line 15, in main
sys.exit(_main())
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/bin/celery.py", line 213, in main
return celery(auto_envvar_prefix="CELERY")
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/click/decorators.py", line 21, in new_func
return f(get_current_context(), *args, **kwargs)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/bin/base.py", line 132, in caller
return f(ctx, *args, **kwargs)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/bin/worker.py", line 326, in worker
**kwargs)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/worker/worker.py", line 99, in __init__
self.setup_instance(**self.prepare_args(**kwargs))
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/worker/worker.py", line 139, in setup_instance
self.blueprint.apply(self, **kwargs)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/bootsteps.py", line 211, in apply
step.include(parent)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/bootsteps.py", line 379, in include
inc, ret = self._should_include(parent)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/bootsteps.py", line 335, in _should_include
return True, self.create(parent)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/worker/components.py", line 238, in create
prefetch_multiplier=w.prefetch_multiplier,
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/bootsteps.py", line 331, in instantiate
return instantiate(name, *args, **kwargs)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/utils/imports.py", line 44, in instantiate
return symbol_by_name(name)(*args, **kwargs)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/worker/consumer/consumer.py", line 212, in __init__
self.blueprint.apply(self, **dict(worker_options or {}, **kwargs))
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/bootsteps.py", line 205, in apply
step = S(parent, **kwargs)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/worker/consumer/control.py", line 25, in __init__
self.box = (pidbox.gPidbox if self.is_green else pidbox.Pidbox)(c)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/worker/pidbox.py", line 28, in __init__
self.node = c.app.control.mailbox.Node(
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/kombu/utils/objects.py", line 43, in __get__
value = obj.__dict__[self.__name__] = self.__get(obj)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/app/base.py", line 1230, in control
return instantiate(self.control_cls, app=self)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/utils/imports.py", line 44, in instantiate
return symbol_by_name(name)(*args, **kwargs)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/kombu/utils/imports.py", line 56, in symbol_by_name
module = imp(module_name, package=package, **kwargs)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/celery/app/control.py", line 9, in <module>
from kombu.matcher import match
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/kombu/matcher.py", line 132, in <module>
for ep, args in entrypoints('kombu.matchers'):
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/kombu/utils/compat.py", line 93, in entrypoints
for ep in importlib_metadata.entry_points().get(namespace, [])
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/importlib_metadata/__init__.py", line 865, in entry_points
return SelectableGroups.load(eps).select(**params)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/importlib_metadata/__init__.py", line 340, in load
ordered = sorted(eps, key=by_group)
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/importlib_metadata/__init__.py", line 863, in <genexpr>
dist.entry_points for dist in unique(distributions())
File "/home/ubuntu/Documents/projects/celery-venv/lib/python3.6/site-packages/importlib_metadata/_itertools.py", line 16, in unique_everseen
k = key(element)
AttributeError: 'PathDistribution' object has no attribute 'name'
I tried to search the error on stackoverflow but could find not much insight about the error. Would appreciate some hint on it
The problem is probably related to importlib-metadata. Try adding a requirement to your venv to restrict it to an earlier version. In a similar case, importlib-metadata<3.4.0 worked for me.
The next release of spacy (v3.0.6) should fix this problem (at least if it's only related to spacy) by removing importlib-metadata as a requirement.
I came across the same error in spacy v3.0.6 too. importlib-metadata==3.4.0 worked for me.
The error was with importlib-metadata==4.0.0
This exact same issue happened to me with spacy v3.4.1. importlib-metadata==3.4.0 while creating the virtual environment fixed the issue for me as well. Interestingly, my importlib-metadata defaulted to 2.0.0 beforehand, even though my python is version 3.9.10.

Is there a safe way to safely delete a Model field in Django?

I'm making a blog application in Django, and I want to modify a field of the Post class:
I want to change the meta_description field to just description.
From:
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
meta_description = models.TextField(blank=True, null=True)
body = models.TextField()
def __str__(self):
"""
Show the title and the author in the admin Page
"""
return self.title + " by " + str(self.author)
def get_absolute_url(self):
return reverse("blog:article_page", kwargs={"pk": self.pk})
⏎
To:
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
description = models.TextField(blank=True, null=True)
body = models.TextField()
def __str__(self):
"""
Show the title and the author in the admin Page
"""
return self.title + " by " + str(self.author)
def get_absolute_url(self):
return reverse("blog:article_page", kwargs={"pk": self.pk})
When I do that in the model: I have an error Making the migration:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/base.py", line 368, in execute
self.check()
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check
all_issues = checks.run_checks(
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 408, in check
for pattern in self.url_patterns:
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 582, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/daniel/MEGA/my-git/github/Developer-road-website/DeveloperRode/DeveloperRode/urls.py", line 26, in <module>
path("blog/", include('blog.urls')),
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/daniel/MEGA/my-git/github/Developer-road-website/DeveloperRode/blog/urls.py", line 2, in <module>
from .views import BlogView, ArticleDetail, PostCreateView, EditPost, PostDeleteView
File "/home/daniel/MEGA/my-git/github/Developer-road-website/DeveloperRode/blog/views.py", line 8, in <module>
from .forms import PostForm, EditForm
File "/home/daniel/MEGA/my-git/github/Developer-road-website/DeveloperRode/blog/forms.py", line 4, in <module>
class PostForm(forms.ModelForm):
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/forms/models.py", line 268, in __new__
raise FieldError(message)
What Can I do?
The reason this happens is because besides models, you likely have forms, views, serializers, etc. that still use meta_description. If you thus have a PostForm like:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['meta_description']
# change to description &uparrow;
then you should alter this to description as well. You thus should perform a search with meta_description through your project and alter the occurrences of meta_description, but be careful: not all the meta_descriptions per see refer to the field of the Post model, if it is about another model, you of course should not modify this.
I solved the Problem, It seem to be a Form problem, where I was calling the Old field meta_description.
I correct it in forms.py file and make the makemigrations command, after that it showed a prompt:
Did you rename post.meta_description to post.description (a TextField)? [y/N] y
And now there the problem is solved.

ImportError: The HttpLocust class has been renamed to HttpUser in version 1.0

I'm quite new to Locust, just started tinkering with it a couple of days ago.
To quick start, i was following someone else example as below,
file : locustfile.py
import random
from locust import HttpLocust, TaskSet, task
class UserBehavior(TaskSet):
def on_start(self):
""" on_start is called when a Locust start before
any task is scheduled
"""
self.login()
def login(self):
self.client.post("/login",
{"username":"ellen_key",
"password":"education"})
#task(2)
def index(self):
self.client.get("/")
#task(1)
def profile(self):
self.client.get("/profile")
class WebsiteUser(HttpLocust):
task_set = UserBehavior
min_wait = 5000
max_wait = 9000
When i run locust from the current directory, i am getting the below exception,
Traceback (most recent call last):
File "/usr/local/bin/locust", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python3.6/dist-packages/locust/main.py", line 113, in main
docstring, user_classes = load_locustfile(locustfile)
File "/usr/local/lib/python3.6/dist-packages/locust/main.py", line 77, in load_locustfile
imported = __import_locustfile__(locustfile, path)
File "/usr/local/lib/python3.6/dist-packages/locust/main.py", line 53, in __import_locustfile__
return source.load_module()
File "<frozen importlib._bootstrap_external>", line 399, in _check_name_wrapper
File "<frozen importlib._bootstrap_external>", line 823, in load_module
File "<frozen importlib._bootstrap_external>", line 682, in load_module
File "<frozen importlib._bootstrap>", line 265, in _load_module_shim
File "<frozen importlib._bootstrap>", line 684, in _load
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/koushic/kk-ldl/locust/locustfile.py", line 19, in <module>
class WebsiteUser(HttpLocust):
File "/usr/local/lib/python3.6/dist-packages/locust/util/deprecation.py", line 23, in __new__
raise ImportError(deprecation_message)
ImportError: The HttpLocust class has been renamed to HttpUser in version 1.0. For more info see: https://docs.locust.io/en/latest/changelog.html#changelog-1-0
Could someone help me to understand the issue here.
Python 3.6.9
pip 20.1.1
Just check the last line of the error message:
ImportError: The HttpLocust class has been renamed to HttpUser in version 1.0. For more info see: https://docs.locust.io/en/latest/changelog.html#changelog-1-0
If you're lucky all you'll need to do is change these two lines:
from locust import HttpUser, TaskSet, task
class WebsiteUser(HttpUser):

Flask/Keras webservice ModuleNotFoundError: No module named 'tensorflow_core.keras'

i'm building a simple webservice to classify an image.
Separated my keras model classifies correctly and the flask service is running.
But when i try to use the keras model in my flask app ...
from flask import Flask
from myproject.keras_model_wrapper import get_result
APP = Flask(__name__)
#APP.route('/')
def keras_result():
return get_result()
if __name__ == 'main':
APP.run()
... an import error occurs.
* Environment: development
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Traceback (most recent call last):
File "<python_path>\python\python37\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<python_path>\python\python37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<project_path>\.venv\Scripts\flask.exe\__main__.py", line 9, in <module>
File "<project_path>\.venv\lib\site-packages\flask\cli.py", line 966, in main
cli.main(prog_name="python -m flask" if as_module else None)
File "<project_path>\.venv\lib\site-packages\flask\cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "<project_path>\.venv\lib\site-packages\click\core.py", line 717, in main
rv = self.invoke(ctx)
File "<project_path>\.venv\lib\site-packages\click\core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "<project_path>\.venv\lib\site-packages\click\core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "<project_path>\.venv\lib\site-packages\click\core.py", line 555, in invoke
return callback(*args, **kwargs)
File "<project_path>\.venv\lib\site-packages\click\decorators.py", line 64, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "<project_path>\.venv\lib\site-packages\click\core.py", line 555, in invoke
return callback(*args, **kwargs)
File "<project_path>\.venv\lib\site-packages\flask\cli.py", line 860, in run_command
extra_files=extra_files,
File "<project_path>\.venv\lib\site-packages\werkzeug\serving.py", line 1008, in run_simple
run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
File "<project_path>\.venv\lib\site-packages\werkzeug\_reloader.py", line 337, in run_with_reloader
reloader.run()
File "<project_path>\.venv\lib\site-packages\werkzeug\_reloader.py", line 202, in run
for filename in chain(_iter_module_files(), self.extra_files):
File "<project_path>\.venv\lib\site-packages\werkzeug\_reloader.py", line 24, in _iter_module_files
filename = getattr(module, "__file__", None)
File "<project_path>\.venv\lib\site-packages\tensorflow\__init__.py", line 50, in __getattr__
module = self._load()
File "<project_path>\.venv\lib\site-packages\tensorflow\__init__.py", line 44, in _load
module = _importlib.import_module(self.__name__)
File "<python_path>\python\python37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'tensorflow_core.keras'
I don't know if it's important that the import system searches out of my .venv
and TBH I have no idea, what exactly I should search for solving it on my own.
Every hint is welcome
I don't consider this to be a solution but Setting flask_debug=1(off) will allow you to continue working but you will need to restart the server after every change.
The issue is being tracked in TensorFlow Repo at the link below.
ModuleNotFoundError: No module named 'tensorflow_core.keras' in Flask
A Workaround that Works perfectly for Flask==1.1.1 and tensorflow==2.1.0
In Flask you should put "import tensorflow as tf" in the "__init__.py" file.
In Django you should put "import tensorflow as tf" in the "manage.py" file.

How to fix this error when starting Django service?--Unhandled exception in thread started by

I'm using python3.6 and Django2.0, but the code is supposed to be written in Django1.x. An error occurred when I tried to start the service. This is my first time to contact Django and I hope to get help.
It should be an error in the urls.py file
This is urls.py. This file in the book of .it's GitHub is https://github.com/ai2010/machine_learning_for_the_web/tree/master/chapter_7/server_movierecsys
#from django.conf.urls import patterns, include, url
from django.conf.urls import include, url
from django.contrib import admin
from books_recsys_app.api import UsersList
import books_recsys_app.views
import rest_framework_swagger
from books_recsys_app.views import home, auth, signout, rate_movie, movies_recs
from rest_framework_swagger.views import get_swagger_view
schema_view = get_swagger_view(title='API name')
urlpatterns = [
url(r'^docs/', schema_view)
]
urlpatterns += [
url(r'^$', home, name='home'),
url(r'^auth/', auth, name='auth'),
url(r'^signout/',signout,name='signout'),
url(r'^rate_movie/',rate_movie,name='rate_movie'),
url(r'^movies-recs/',movies_recs,name='movies_recs'),
url(r'^admin/', include(admin.site.urls)),
url(r'^users-list/',UsersList.as_view(),name='users-list')
]
This error Message,when I run "python3 manage.py runserver localhost:8000"
Performing system checks...
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10b52abf8>
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 379, in check
include_deployment_checks=include_deployment_checks,
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 366, in _run_checks
return checks.run_checks(**kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/registry.py", line 71, in run_checks
new_errors = check(app_configs=app_configs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 533, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 526, in urlconf_module
return import_module(self.urlconf_name)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "/Users/changxuan/PycharmProjects/reconmendationSystem/server_movierecsys/server_movierecsys/urls.py", line 5, in <module>
import books_recsys_app.views
File "/Users/changxuan/PycharmProjects/reconmendationSystem/server_movierecsys/books_recsys_app/views.py", line 17, in <module>
from sklearn.feature_extraction.text import TfidfVectorizer
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/feature_extraction/__init__.py", line 10, in <module>
from . import text
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/feature_extraction/text.py", line 30, in <module>
from ..preprocessing import normalize
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/preprocessing/__init__.py", line 6, in <module>
from ._function_transformer import FunctionTransformer
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/preprocessing/_function_transformer.py", line 5, in <module>
from ..utils.testing import assert_allclose_dense_sparse
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/utils/testing.py", line 26, in <module>
from urllib2 import urlopen
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/urllib2.py", line 220
raise AttributeError, attr
^
SyntaxError: invalid syntax
The error occurred because urllib2 was referenced in the sklearn library and datasets library. I'm just going to change the code in the file
Original 24-31 contents:
Try:
# Python 2
The from urllib2 import urlopen
The from urllib2 import HTTPError
Except ImportError:
# Python 3 +
The from urllib. Request the import urlopen
The from urllib. Error import HTTPError
Reason: the contents of urllib2 are removed because of an error in python3.x
Now:
# Python 3 +
The from urllib. Request the import urlopen
The from urllib. Error import HTTPError

Resources