PyLaTeX: pylatex.errors.CompilerError: No LaTex compiler was found - python

I am trying to run the exact code from here to get an example of pylatex working.
In the directory that I am working in, I have copied and pasted from the link:
from pylatex import Document, Section, Subsection, Command
from pylatex.utils import italic, NoEscape
import pdflatex
def fill_document(doc):
"""Add a section, a subsection and some text to the document.
:param doc: the document
:type doc: :class:`pylatex.document.Document` instance
"""
with doc.create(Section('A section')):
doc.append('Some regular text and some ')
doc.append(italic('italic text. '))
with doc.create(Subsection('A subsection')):
doc.append('Also some crazy characters: $&#{}')
if __name__ == '__main__':
# Basic document
doc = Document('basic')
fill_document(doc)
doc.generate_pdf(clean_tex=False,compiler='pdflatex')
doc.generate_tex()
# Document with `\maketitle` command activated
doc = Document()
doc.preamble.append(Command('title', 'Awesome Title'))
doc.preamble.append(Command('author', 'Anonymous author'))
doc.preamble.append(Command('date', NoEscape(r'\today')))
doc.append(NoEscape(r'\maketitle'))
fill_document(doc)
doc.generate_pdf('basic_maketitle', clean_tex=False)
# Add stuff to the document
with doc.create(Section('A second section')):
doc.append('Some text.')
doc.generate_pdf('basic_maketitle2', clean_tex=False)
tex = doc.dumps() # The document as string in LaTeX syntax
I consistently get the error:
Traceback (most recent call last):
File "test.py", line 26, in <module>
doc.generate_pdf(clean_tex=False,compiler='pdflatex')
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.7/site-packages/pylatex/document.py", line 280, in generate_pdf
'Either specify a LaTex compiler ' +
pylatex.errors.CompilerError: No LaTex compiler was found
You can see some of the things I've tried based on other people's suggestions:
1. if I just open a python console in this directory, and type:
from pylatex import Document, Section, Subsection, Command
from pylatex.utils import italic, NoEscape
import pdflatex
there are no errors, implying importing was successful.
I saw another recommendation that perl must be installed, which it is:
localhost:test1$ perl --version : returns info about perl
I've specified the compiler as was suggested elsewhere on StackOverflow: 'doc.generate_pdf(clean_tex=False,compiler='pdflatex')'
What else can I do? The ultimate aim is I have generated strings and an image with python, and I want to put them both into a PDF and format, in case there is a better alternative that anyone can suggest. P.s. I'm aware of the tex stack exchange, but I specifically need a way for latex to interact with python, which is why I asked here.

Apparantly you'll need to run these two apt-get dependencies
sudo apt-get install latexmk
sudo apt-get install -y texlive-latex-extra
also install pdflatex with pip
pip install pdflatex
then use
doc.generate_pdf(compiler='pdflatex')

For me, on CentOS 8, I had to run:
pip install pylatex
sudo dnf install texlive
sudo dnf install texlive-lastpage
Then it worked for me.

I had this same error and my problem was that I had forgotten to add pdflatex (through MiKTex) to my environment path in Windows. My code worked after reloading my terminal. I have not installed Perl by the way.

Related

How to install utils.lib in anaconda to run a jupyter notebook for python?

In a jupyter notebook running on anaconda there is a line "import utils.lib as lib". When I run it, I get the error message "ModuleNotFoundError: No module named 'utils.lib'".
I tried to search for the utils.lib on Internet so that I can install it. But I could not find it. Please let me know how to install it. Thank you -- Manoranjan Dash
You don't provide the code context for the import line. You don't have to always provide the complete context; however, you didn't provide anything and that is why the Bot tried to encourage you to improve things. 'Additional context' would also be important to supply in your post such as the source of the notebook or any related blog post, etc..
The only place I see that import come up on the internet besides your post is here. The code there shows how to get that and install it under 'Downloading the utils and installing':
LIB_DIRECTORY_PATH = DIR+'/utils'
# Check if utils directory already exist, otherwise download, and install
import os
import shutil
if not os.path.isdir(LIB_DIRECTORY_PATH):
if not os.path.isdir(DIR+'/utils'):
os.mkdir(DIR+'/utils')
print('Downloading utils')
user = "ruslanmv"
repo = "Speech-Recognition-with-RNN-Neural-Networks"
src_dir = "utils"
pyfile = "lib.py"
url = f"https://raw.githubusercontent.com/{user}/{repo}/master/{src_dir}/{pyfile}"
!wget --no-cache --backups=1 {url}
print("Installing library...")
shutil.move(DIR+'/lib.py', DIR +'/utils/lib.py')
print("Done.")
Source of that above code: https://ruslanmv.com/blog/Speech-Recognition-with-RNN-Neural-Networks
Code that the code block retrieves and places in the correct location is found at this repo. It isn't something you install. You need to place it alongside the notebok. (Ideally it is set up so you just download or clone the repository, it looks like to me.) The utils directory and it's content is what you need to get or make/copy and place along with your notebook.
Direct link to raw code it gets:
https://raw.githubusercontent.com/ruslanmv/Speech-Recognition-with-RNN-Neural-Networks/master/utils/lib.py

ModuleNotFoundError: No module named 'object_detection'

i try to train.py in object_detection in under git url
https://github.com/tensorflow/models/tree/master/research/object_detection
However, the following error occurs.
ModuleNotFoundError: No module named 'object_detection'
So I tried to solve the problem by writing the following code.
import sys
sys.path.append('/home/user/Documents/imgmlreport/inception/models/research/object_detection')
from object_detection.builders import dataset_builder
This problem has not been solved yet.
The directory structure is shown below.
~/object_detection/train.py
~/object_detection/builders/dataset_bulider.py
and here is full error massage
/home/user/anaconda3/lib/python3.6/site-packages/h5py/init.py:34: FutureWarning: Conversion of the second argument of issubdtype from float to np.floating is deprecated.
In future, it will be treated as np.float64 == np.dtype(float).type.
from ._conv import register_converters as _register_converters
Traceback (most recent call last):
File "train.py", line 52, in
import trainer
File"/home/user/Documents/imgmlreport/inception/models/research/object_detection/trainer.py", line 26, in
from object_detection.builders import optimizer_builder
ModuleNotFoundError: No module named 'object_detection'
how can i import modules?
Try install Tensorflow Object Detection Library Packaged
pip install tensorflow-object-detection-api
Cause of this error is installing object_detection library, So one of the solution which can work is running the below command inside models/research
sudo python setup.py install
If such solution does not work, please execute the below command one by one in the directory models/research
export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
sudo python setup.py install
I hope this will work. I also faced the same problem while creating model from export_inference_graph.py. It worked for me.
You need to export the environmental variables every time you open a new terminal in that environment.
Please note that there are are back quotes on each of the pwd in the command as this might not be showing in the command below. Back quote is the same as the tilde key without pressing the shift key (US keyboard).
From tensorflow/models/research/
export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
try this:
python setup.py build
python setup.py install
There are a number of modules in the object_detection folder, and I have created setup.py in the parent directory(research folder) to import all of them.
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['Pillow>=1.0', 'Matplotlib>=2.1', 'Cython>=0.28.1']
setup(
name='object_detection',
version='0.1',
install_requires=REQUIRED_PACKAGES,
include_package_data=True,
packages=[p for p in find_packages() if p.startswith('object_detection')],
description='Tensorflow Object Detection Library',
)
You did have "sys.path.append()" before you imported the object detection, so I am surprised that you are facing this error!
Please check that the path you have used in sys.path.append() is right.
Well, the only and obvious answer for the error is that the path of the module is not added properly.
Besides the various ways mentioned here, here is a way in which you can add the "object_detection" path permanently to the PYTHONPATH variable.
If you are using a Linux system, here is how you would go about it:
Go to the Home directory. Press Ctrl + H to show hidden files. You will see a file called ".bashrc". Open this file using a code editor (I used Visual Studio).
In the last line of .bashrc file, add the line:
export PYTHONPATH=/your/module/path:/your/other/module/path:your/someother/module/path
Then press "save" in the code editor. Since ".bashrc" is a "Read-only" file the editor will throw a pop-up saying the same. Also in the pop-up there will be an option that says: "Try with sudo". Hit this button and now you are good to go.
All your modules are now permanently added to the PYTHONPATH. This means that you need not run sys.path.append every time you open your terminal and start a session!
Below is the screenshot with no error when I followed the said steps:
Try this. I hope it helps.
And finally, If you've followed all the steps here and are at your wit's end...make sure the file that you're running (the one with your source code in it ya know), isn't named object_detection.py - that would preclude it being searched for as a module.
Certainly I've never done anything like this that led me to add an embarrassing answer on Stack Overflow...
I had to do:
sudo pip3 install -e . (ref)
sudo python3 setup.py install
System:
OS: Ubuntu 16.04, Anaconda (I guess this is why I need to use pip3 and python3 even I made virtual environment with Pyehon 3.8)

Symbol not found: _PyObject_REPR when calling pyobjc function, Python3.5.1

Been looking to get started w/ pyobjc in order to simulate some mouse-events/keystrokes equivalent to ctypes on windows. Ran a clean install of pyobjc (pyobjc-core was downloaded first, then pyobjc). Below is the code that I have been trying out (source):
from Quartz.CoreGraphics import CGEventCreateMouseEvent
from Quartz.CoreGraphics import CGEventPost
from Quartz.CoreGraphics import kCGEventMouseMoved
from Quartz.CoreGraphics import kCGEventLeftMouseDown
from Quartz.CoreGraphics import kCGEventLeftMouseDown
from Quartz.CoreGraphics import kCGEventLeftMouseUp
from Quartz.CoreGraphics import kCGMouseButtonLeft
from Quartz.CoreGraphics import kCGHIDEventTap
def mouseEvent(type, posx, posy):
theEvent = CGEventCreateMouseEvent(
None,
type,
(posx,posy),
kCGMouseButtonLeft)
CGEventPost(kCGHIDEventTap, theEvent)
def mousemove(posx,posy):
mouseEvent(kCGEventMouseMoved, 845, 396);
def mouseclick(posx,posy):
mouseEvent(kCGEventMouseMoved, 845, 396);
mouseEvent(kCGEventLeftMouseDown, 845, 396);
mouseEvent(kCGEventLeftMouseUp, 845, 396);
Which yields the following error as most recent:
File "/usr/local/lib/python3.5/site-packages/objc/__init__.py", line 15, in _update
import objc._objc as _objc
ImportError: dlopen(/usr/local/lib/python3.5/site-packages/objc/_objc.cpython-35m-darwin.so, 2): Symbol not found: _PyObject_REPR
Referenced from: /usr/local/lib/python3.5/site-packages/objc/_objc.cpython-35m-darwin.so
Expected in: flat namespace
in /usr/local/lib/python3.5/site-packages/objc/_objc.cpython-35m-darwin.so
Clearly the issue is that _PyObject_REPR is absent from Python3.5, and so the init script fails. Having gone on the bitbucket 'issues' page, I found this. One of the users (Kentzo) amended the pyobjc github to remove the involvement of _PyObject_REPR.
My question: how do I go about correctly installing his amended version? I have attempted the standard 'pip3 install "link"' method, however I cannot seem to install it over my existing pyobjc files. Do I need to manually remove all of the pyobjc files via sudo?
As you can probably tell I'm a bit of a noob, so any guidance would be much appreciated!
Thanks!
To install a working version, you will want to download the correct pyobjc version (Kentzo's), navigate to the downloaded folder in terminal or the command line, and run "python3 setup.py install" from terminal (Mac) or "setup.py install" from the command line (Windows). The setup.py file will handle everything for you.
Download Kentzo's version here, and then open it: https://github.com/GreatFruitOmsk/pyobjc-core/releases/download/v3.0.5.dev0/pyobjc-core-3.0.5.tar.gz.
Once you've opened that downloaded folder, follow the instructions from this page under the Distutils section: https://docs.python.org/2/install/#the-new-standard-distutils.
I don't know whether already having the old pyobjc version will cause trouble, but go ahead and uninstall the previous pyobjc version (with pip3 uninstall like usual), and then start the above steps.

ImportError: No module named stack

I have a code in python that I have been working on and it builds and runs very well on my pc (Windows). I had to run the same code on my other machine which runs ubuntu,so I had to install all the packages on prior to runing the code. The problem is I ran into this error which I couldn't figure out. The error is triggered by one of the installed packages.
from qalsadi import analex
File "/usr/local/lib/python2.7/dist-packages/qalsadi/analex.py", line 14, in <module>
import pyarabic.araby as araby # basic arabic text functions
File "/usr/local/lib/python2.7/dist-packages/pyarabic/araby.py", line 28, in <module>
from stack import *
ImportError: No module named stack
I used the following command, "sudo pip install pyarabic", to install it. However, still the file stack.py doesn't exist among it's files. I searched in the folder /usr/local/lib/python2.7/dist-packages/pyarabic. The folder contains the following: araby.py and init.py and the coresponding pyc files only. I'v insalled and uninstalled it a number of times using "pip" but still the file is not there.
Check your pyarabic folder. Usually it's in Python27\Lib\site-packages\pyarabic.
There, there should be stack.py. If it doesn't exists, re-download pyarabic and then reinstall it.
After installation of pyarabic import STACK in this manner:
from pyarabic.stack import Stack
for window users
open cmd prompt and type the following to install the stack variable to python 3.x-
pip install pyarabic
To install and run with this code-
from pyarabic.stack import Stack
It seems like stack is not part of the Python Package Index so most probably it is a script you installed manually. The problem can be that the folder containing stack.py is not on your PYTHONPATH.
Open a terminal (Ctrl+ Alt + t) and edit the .bashrc file:
sudo gedit ~/.bashrc
Add the following line:
export PYTHONPATH=$PYTHONPATH:/path/to/the/folder/of/your/module
where you should substitute the part after the : to the full path to the directory
where stack.py can be found.
I hope this helps.

GeoDjango GEOSException error

Trying to install a GeoDjango on my machine. I'm really new to Python and being brought into a project that has been a very tricky install for the other team members. I installed Python 2.7 and GEOS using brew, and running PSQL 9.2.4 but keep getting this error when I try to get the webserver running:
__import__(name)
File "/Users/armynante/Desktop/uclass-files/uclass-env/lib/python2.7/site
packages/django/contrib/gis/geometry/backend/geos.py", line 1, in <module>
from django.contrib.gis.geos import (
File "/Users/armynante/Desktop/uclass-files/uclass-env/lib/python2.7/site
packages/django/contrib/gis/geos/__init__.py", line 6, in <module>
from django.contrib.gis.geos.geometry import GEOSGeometry, wkt_regex, hex_regex
File "/Users/armynante/Desktop/uclass-files/uclass-env/lib/python2.7/site
packages/django/contrib/gis/geos/geometry.py", line 14, in <module>
from django.contrib.gis.geos.coordseq import GEOSCoordSeq
File "/Users/armynante/Desktop/uclass-files/uclass-env/lib/python2.7/site-
packages/django/contrib/gis/geos/coordseq.py", line 9, in <module>
from django.contrib.gis.geos.libgeos import CS_PTR
File "/Users/armynante/Desktop/uclass-files/uclass-env/lib/python2.7/site-
packages/django/contrib/gis/geos/libgeos.py", line 119, in <module>
_verinfo = geos_version_info()
File "/Users/armynante/Desktop/uclass-files/uclass-env/lib/python2.7/site
packages/django/contrib/gis/geos/libgeos.py", line 115, in geos_version_info
if not m: raise GEOSException('Could not parse version info string "%s"' % ver)
django.contrib.gis.geos.error.GEOSException: Could not parse version info string
"3.4.2-CAPI-1.8.2 r3921"
Cant seem to find anything relevant to this trace on SO or the web. I think it might be a regex failure? I'm currently trying to reinstall PSQL and GEOS to see if I can get it running.
Here is my requirements file:
django==1.4
psycopg2==2.4.4
py-bcrypt==0.4
python-memcached==1.48
south==0.7.3
# Debug Tools
sqlparse==0.1.3
django-debug-toolbar==0.9.1
django-devserver==0.3.1
# Deployment
fabric==1.4
# AWS
# boto==2.1.1
django-storages==1.1.4
django-ses==0.4.1
# ECL
http://packages.elmcitylabs.com/ecl_django-0.5.3.tar.gz#ecl_django
http://packages.elmcitylabs.com/ecl_google-0.2.14.tar.gz#ecl_google
# https://packages.elmcitylabs.com/ecl_tools-0.3.7.tar.gz#ecl_tools
# https://packages.elmcitylabs.com/chargemaster-0.2.19.tar.gz
# https://packages.elmcitylabs.com/ecl_facebook-0.3.12.tar.gz#ecl_facebook
# https://packages.elmcitylabs.com/ecl_twitter-0.3.3.tar.gz#ecl_twitter
# Search
#https://github.com/elmcitylabs/django-haystack/tarball/issue-522#django-haystack
-e git+https://github.com/toastdriven/django-haystack.git#egg=django-haystack
pysolr==2.1.0-beta
# whoosh==2.3.2
# Misc
# PIL
# django-shorturls==1.0.1
# suds==0.4
django-mptt
sorl-thumbnail
stripe
pytz==2013b
This is my solution (obviously it is ugly, like my English, but works).
The problem is that the versions string has an white space unwanted in the RegEx.
The error says:
GEOSException: Could not parse version info string "3.4.2-CAPI-1.8.2 r3921"
And the geos_version_info warns:
Regular expression should be able to parse version strings such as
'3.0.0rc4-CAPI-1.3.3', '3.0.0-CAPI-1.4.1' or '3.4.0dev-CAPI-1.8.0'
Edit this file: site-packages/django/contrib/gis/geos/libgeos.py
Look for the function: geos_version_info
And change this line:
ver = geos_version().decode()
With this line:
ver = geos_version().decode().split(' ')[0]
There is also another problem, where there is a whitespace at the end but no more information is provided. Such version also doesn't match version regular expression, so strip()-ping the version may be expected behaviour as a quick fix. In my example it was: '3.8.0-CAPI-1.13.1 '
In the latest GEOS install, the above answer didn't work... but was close to the problem.
I changed the regex right above the geos_version_info():
from:
version_regex = re.compile(r'^(?P<version>(?P<major>\d+)\.(?P<minor>\d+)\.(?P<subminor>\d+))((rc(?P<release_candidate>\d+))|dev)?-CAPI-(?P<capi_version>\d+\.\d+\.\d+)$')
to be:
version_regex = re.compile(r'^(?P<version>(?P<major>\d+)\.(?P<minor>\d+)\.(?P<subminor>\d+))((rc(?P<release_candidate>\d+))|dev)?-CAPI-(?P<capi_version>\d+\.\d+\.\d+).*$')
Notice the .* added to the end of the regex.
I think this is broken again. A recent upgrade on our FreeBSD server led to this error:
django.contrib.gis.geos.error.GEOSException: Could not parse version info string "3.6.2-CAPI-1.10.2 4d2925d6"
Looks like the regex in Django's libgeos.py needs to be updated again to account for this different syntax. Nachopro's solution still serves as a workaround.
It appears that this has been fixed in Django as of last March or so. See also Django bug 20036. So upgrading to Django 1.5.4 will solve the problem.
For those folks who don't have 3.6.1 previously installed:
brew unlink geos
Install 3.6.1 with brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/145b22e8330e094ee148861e72e26c03e73d34a1/Formula/geos.rb.
brew info geos should show 3.6.1 starred:
Brew just released geos 3.8.0 that of course breaks Django 1.11 again.
The previous version, 3.7.3, was oh so very helpfully cleared by the all new all automatic cleanup now running on upgrades, so no brew switch geos 3.7.3 for me.
I ended up using this post to understand how to find the previous version number and commit hash:
cd $( brew --prefix )/Homebrew/Library/Taps/homebrew/homebrew-core
git log -- Formula/geos.rb | less
# find the version you need in the file, copy its hash
brew unlink geos
brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/<yourcommithash>/Formula/geos.rb
After all this, the download for geos 3.7.3 fails SHA256 checksum validation for some reason... so I ended up trying 3.7.2, that actually worked.
For now the command to reinstall 3.7.2 on Catalina is:
brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/823b700ab61eeec57f34d50be2cc34a285fb5abc/Formula/geos.rb
If one cannot for any reason edit the site packages themselves, this ugly hack did it for me without having to act on the environment itself:
try:
__import__('django.contrib.gis.geos.libgeos', fromlist=['version_regex'])
except Exception as e:
import re
att = __import__('django.contrib.gis.geos.libgeos', fromlist=['version_regex'])
setattr(att, 'version_regex', re.compile(
'^(?P<version>(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<subminor>\\d+))((rc(?P<release_candidate>\\d+))|dev)?-CAPI-(?P<capi_version>\\d+\\.\\d+\\.\\d+)( r\\d+)?( \\w+)?.*$'))
assert str(type(e)) == "<class 'django.contrib.gis.geos.error.GEOSException'>", str(e)
It is based on JayCrossler's answer.
Update
The above executes code found within the django.contrib.gis.geos.__init__.py module, which already tries to use the problematic part, rendering the above solution unusable (for python 2.7+). This can be worked around as:
import sys
try:
import django.contrib.gis.geos.libgeos
except Exception as e:
import re
setattr(sys.modules['django.contrib.gis.geos.libgeos'],'version_regex', re.compile(
'^(?P<version>(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<subminor>\\d+))((rc(?P<release_candidate>\\d+))|dev)?-CAPI-(?P<capi_version>\\d+\\.\\d+\\.\\d+)( r\\d+)?( \\w+)?.*$'))
assert str(type(e)) == "<class 'django.contrib.gis.geos.error.GEOSException'>", str(e)
Where basically we are acting directly on the module in sys.modules instead of trying to get it from another import that will fail.
This can be fixed by trying the following,
brew switch geos 3.6.1
I fixed the issue by installing PostGIS with Postgres using https://postgresapp.com/downloads.html.
Install PostGIS (2.2): brew install postgis
To unlink geos if version is higher than 3.6.1: brew unlink geos
Install Geos (3.6.1): brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/145b22e8330e094ee148861e72e26c03e73d34a1/Formula/geos.rb
Switch geos version(latest version is 3.7.2 which is not supported by Django 1.11.3): brew switch geos 3.6.1
Login to database and create postgis extensions: CREATE EXTENSION postgis;
Test postgis extension: SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geography, 'POINT(-21.96 64.15)'::geography);
Check postgis version: SELECT PostGIS_full_version();

Categories