python error on barcode generation - python

I am using python 2.7 and pyBarcode 0.7 in Windows and I am trying to generate barcode as png image by using following sample code (available in pyBarcode webpage)
>>> import barcode
>>> barcode.PROVIDED_BARCODES
[u'code39', u'ean', u'ean13', u'ean8', u'gs1', u'gtin', u'isbn', u'isbn10',
u'isbn13', u'issn', u'jan', u'pzn', u'upc', u'upca']
>>> EAN = barcode.get_barcode_class('ean13')
>>> EAN
<class 'barcode.ean.EuropeanArticleNumber13'>
>>> ean = EAN(u'5901234123457')
>>> ean
<barcode.ean.EuropeanArticleNumber13 object at 0x00BE98F0>
# Example with PNG
>>> from barcode.writer import ImageWriter
>>> ean = EAN(u'5901234123457', writer=ImageWriter())
>>> fullname = ean.save('ean13_barcode')
Last line generates following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\python27\lib\site-packages\barcode\base.py", line 68, in save
output = self.render(options)
File "c:\python27\lib\site-packages\barcode\ean.py", line 106, in render
return Barcode.render(self, options)
File "c:\python27\lib\site-packages\barcode\base.py", line 103, in render
raw = Barcode.raw = self.writer.render(code)
File "c:\python27\lib\site-packages\barcode\writer.py", line 188, in render
self._callbacks['paint_text'](xpos, ypos)
File "c:\python27\lib\site-packages\barcode\writer.py", line 280, in _paint_te
xt
font = ImageFont.truetype(FONT, self.font_size * 2)
File "c:\python27\lib\site-packages\PIL\ImageFont.py", line 218, in truetype
return FreeTypeFont(filename, size, index, encoding)
File "c:\python27\lib\site-packages\PIL\ImageFont.py", line 134, in __init__
self.font = core.getfont(file, size, index, encoding)
File "c:\python27\lib\site-packages\PIL\ImageFont.py", line 34, in __getattr__
raise ImportError("The _imagingft C module is not installed")
ImportError: The _imagingft C module is not installed
I retried by installing Pillow (but before that I removed PIL); I downloaded "Pillow-4.2.1-win32-py2_7.exe"
and I did also "pip install Pillow".
Now when I try to run
import barcode
I got:
File "barcode\codex.py", line 12, in <module>
from barcode.base import Barcode
File "barcode\base.py", line 9, in <module>
from barcode.writer import SVGWriter
File "barcode\writer.py", line 12, in <module>
import Image, ImageDraw, ImageFont
File "c:\python27\lib\site-packages\PIL\Image.py", line 27, in <module>
from . import VERSION, PILLOW_VERSION, _plugins
ValueError: Attempted relative import in non-package
What should I do ?
thanks

Related

Geopandas not working after importing a file from a different directory

I am trying to make a map in python using shapefiles I have downloaded from bbike.org. Here is my code:
import geopandas as gpd
import os
import sys
import matplotlib.pyplot as plt
bos_files_list = ['buildings.shx', 'landuse.shx', 'natural.shx', 'places.shx', 'points.shx', 'railways.shx', 'roads.shx']
cur_path = os.path.dirname(__file__)
def maps_of_bos(files):
for x in range(len(files)):
os.chdir(f'location/of/file')
f = open(f'{files[x]}', 'r')
gpd.read_file(f)
z = maps_of_bos(bos_files_list)
z.plot()
plt.show()
However, my error output is as follows:
Traceback (most recent call last):
File "test.py", line 16, in <module>
z = maps_of_bos(bos_files_list)
File "test.py", line 13, in maps_of_bos
gpd.read_file(f)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/geopandas/io/f
ile.py", line 76, in read_file
with reader(path_or_bytes, **kwargs) as features:
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/contextlib.py", line 113, in
__enter__
return next(self.gen)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/fiona/__init__
.py", line 206, in fp_reader
dataset = memfile.open()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/fiona/io.py",
line 63, in open
return Collection(vsi_path, 'w', crs=crs, driver=driver,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/fiona/collecti
on.py", line 126, in __init__
raise DriverError("no driver")
fiona.errors.DriverError: no driver
I am relatively new to python, and don't really understand my error. can someone please help me?
According to the docs read_file should take the path to the file not an object.
gpd.read_file(f'{files[x]}')
you dont need
f = open(f'{files[x]}', 'r')

Report Lab is not producing/saving a pdf file

Report lab is not producing a pdf in a very simple example/try:
from arcpy import *
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from pyPdf import PdfFileWriter, PdfFileReader
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, cm
from reportlab.platypus import Paragraph
from reportlab.lib import colors
from reportlab.pdfgen import canvas
filename = "HelloWorld.pdf"
c = canvas.Canvas(filename)
c.drawString(100,750,"Welcome to Reportlab!")
c.save()
These two lines work fine:
c.drawString(100,750,"Welcome to Reportlab!")
c.save()
But is this one that throw the errors. I've tried to change the path, the filename, try the 'r' before the string of text for the path+filename, nothing works.
I've got this error trace:
Traceback (most recent call last):
File "C:\Users\Edmundo\GIS_SEG\EGtemp\PdfReports\PyScripts\TestRepLab.py", line 15, in <module>
c.save()
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfgen\canvas.py", line 1237, in save
self._doc.SaveToFile(self._filename, self)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 221, in SaveToFile
data = self.GetPDFData(canvas)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 246, in GetPDFData
return self.format()
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 423, in format
IOf = IO.format(self)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 871, in format
fcontent = format(self.content, document, toplevel=1) # yes this is at top level
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 80, in format
f = element.format(document)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 1561, in format
return PD.format(document)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 679, in format
L = [(format(PDFName(k),document)+b" "+format(dict[k],document)) for k in keys]
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 80, in format
f = element.format(document)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 610, in format
s.decode('pdfdoc')
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\rl_codecs.py", line 1047, in _rl_codecs
if name.startswith(e): return RL_Codecs.__rl_codecs(e)
AttributeError: 'NoneType' object has no attribute '_RL_Codecs__rl_codecs'
You need to call showPage():
from reportlab.pdfgen import canvas
filename = "HelloWorld.pdf"
c = canvas.Canvas(filename)
c.drawString(100,750,"Welcome to Reportlab!")
c.showPage()
c.save()

use polyglot package for Named Entity Recognition in hebrew

I am trying to use the polyglot package for Named Entity Recognition in hebrew.
this is my code:
# -*- coding: utf8 -*-
import polyglot
from polyglot.text import Text, Word
from polyglot.downloader import downloader
downloader.download("embeddings2.iw")
text = Text(u"in france and in germany")
print(type(text))
text2 = Text(u"נסעתי מירושלים לתל אביב")
print(type(text2))
print(text.entities)
print(text2.entities)
this is the output:
<class 'polyglot.text.Text'>
<class 'polyglot.text.Text'>
[I-LOC([u'france']), I-LOC([u'germany'])]
Traceback (most recent call last):
File "C:/Python27/Lib/site-packages/IPython/core/pyglot.py", line 15, in <module>
print(text2.entities)
File "C:\Python27\lib\site-packages\polyglot\decorators.py", line 20, in __get__
value = obj.__dict__[self.func.__name__] = self.func(obj)
File "C:\Python27\lib\site-packages\polyglot\text.py", line 132, in entities
for i, (w, tag) in enumerate(self.ne_chunker.annotate(self.words)):
File "C:\Python27\lib\site-packages\polyglot\decorators.py", line 20, in __get__
value = obj.__dict__[self.func.__name__] = self.func(obj)
File "C:\Python27\lib\site-packages\polyglot\text.py", line 100, in ne_chunker
return get_ner_tagger(lang=self.language.code)
File "C:\Python27\lib\site-packages\polyglot\decorators.py", line 30, in memoizer
cache[key] = obj(*args, **kwargs)
File "C:\Python27\lib\site-packages\polyglot\tag\base.py", line 191, in get_ner_tagger
return NEChunker(lang=lang)
File "C:\Python27\lib\site-packages\polyglot\tag\base.py", line 104, in __init__
super(NEChunker, self).__init__(lang=lang)
File "C:\Python27\lib\site-packages\polyglot\tag\base.py", line 40, in __init__
self.predictor = self._load_network()
File "C:\Python27\lib\site-packages\polyglot\tag\base.py", line 109, in _load_network
self.embeddings = load_embeddings(self.lang, type='cw', normalize=True)
File "C:\Python27\lib\site-packages\polyglot\decorators.py", line 30, in memoizer
cache[key] = obj(*args, **kwargs)
File "C:\Python27\lib\site-packages\polyglot\load.py", line 61, in load_embeddings
p = locate_resource(src_dir, lang)
File "C:\Python27\lib\site-packages\polyglot\load.py", line 43, in locate_resource
if downloader.status(package_id) != downloader.INSTALLED:
File "C:\Python27\lib\site-packages\polyglot\downloader.py", line 738, in status
info = self._info_or_id(info_or_id)
File "C:\Python27\lib\site-packages\polyglot\downloader.py", line 508, in _info_or_id
return self.info(info_or_id)
File "C:\Python27\lib\site-packages\polyglot\downloader.py", line 934, in info
raise ValueError('Package %r not found in index' % id)
ValueError: Package u'embeddings2.iw' not found in index
The english worked but not the hebrew.
Whether I try to download the package u'embeddings2.iw' or not I get:
ValueError: Package u'embeddings2.iw' not found in index
I got it!
It seems like a bug to me.
The language detection defined the language as 'iw' which is the The former ISO 639 language code for Hebrew, and was changed to 'he'.
The text.entities did not recognize the iw code, so i changes it like so:
text2.hint_language_code = 'he'

How do I use reportlab's drawImage with an image url?

When I try the following:
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas
import urllib
import StringIO
import PIL.Image
image_file = urllib.urlopen('https://www.google.com/images/srpr/logo11w.png')
image_string = StringIO.StringIO(image_file.read())
logo = PIL.Image.open(image_string)
canvas = Canvas('output.pdf', pagesize=letter)
canvas.drawImage(logo, 10, 10)
canvas.showPage()
canvas.save()
I get this error:
Traceback (most recent call last):
File "imagefromurl.py", line 12, in <module>
canvas.drawImage(logo, 10, 10)
File "/usr/lib/python2.7/dist-packages/reportlab/pdfgen/canvas.py", line 857, in drawImage
imgObj = pdfdoc.PDFImageXObject(name, image, mask=mask)
File "/usr/lib/python2.7/dist-packages/reportlab/pdfbase/pdfdoc.py", line 2090, in __init__
ext = string.lower(os.path.splitext(source)[1])
File "/usr/lib/python2.7/posixpath.py", line 96, in splitext
return genericpath._splitext(p, sep, altsep, extsep)
File "/usr/lib/python2.7/genericpath.py", line 91, in _splitext
sepIndex = p.rfind(sep)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 515, in __getattr__
raise AttributeError(name)
Reportlab is version 2.5.
I was doing it the hard way. This works (also added the necessary mask to avoid transparent becoming black):
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.utils import ImageReader
logo = ImageReader('https://www.google.com/images/srpr/logo11w.png')
canvas = Canvas('output.pdf', pagesize=letter)
canvas.drawImage(logo, 10, 10, mask='auto')
canvas.showPage()
canvas.save()
Though the hard way would have allowed me to detect a failure to fetch the image url and handle it (e.g. substituting a local image), and this doesn't.

Mistake in Spyder setting

I have a little problem in using Spyder to run a python program:
This is my program:
from PySide.QtGui import QApplication
from pyoppinet.helper.correlation_manager import *
import pyoppinet.network as nt
import numpy as np
from pyoppinet.node import node
from pyoppinet.GUI import network_view as nw
from pyoppinet.pipe.flowline import Flowline
network = nt.PipeLineNetwork(1000.2000)
source1 = node.Source(10,200)
source1.name = 'source1'
source2 = node.Source(150,500)
source2.name = 'source2'
source3 = node.Source(200,400)
source3.name = 'source3'
junction1 =node.Junction(150,600)
junction1.name = 'junction'
sink =node.Sink(300,800)
sink.name = 'sink'
for n in [source1,source2,source3,junction1,sink]:
network.add_node(n)
fl1=Flowline(source1,junction1)
fl2=Flowline(junction1,sink)
fl3=Flowline(source2,sink)
fl4=Flowline(source2,junction1)
fl5=Flowline(source3,sink)
fl6=Flowline(source3,junction1)
for n in [fl1,fl2,fl3,fl4,fl5,fl6]:
network.add_flowline(n)
print [n.name for n in network.get_nodes()]
print 'topological sort', [n.name for n in network.topological_sort()]
a=QApplication([])
view=nw.PipeLineNetworkView(network)
view.show()
a.exec_()
These two rows:
from pyoppinet.helper.correlation_manager import *
import numpy as np
are error.
And the error is:
Traceback (most recent call last):
File "D:\program oppinet\latihan\latihan.py", line 9, in <module>
from pyoppinet.helper.correlation_manager import *
File "D:\program oppinet\pyoppinet\__init__.py", line 1, in <module>
import GUI
File "D:\program oppinet\pyoppinet\GUI\__init__.py", line 7, in <module>
"""
File "D:\program oppinet\pyoppinet\GUI\viewmodelbase.py", line 1, in <module>
File "D:\program oppinet\pyoppinet\GUI\framework\__init__.py", line 3, in <module>
# Copyright © 2011 Pierre Raybaut
File "D:\program oppinet\pyoppinet\GUI\framework\GUI_helper.py", line 1, in <module>
File "D:\program oppinet\pyoppinet\helper\__init__.py", line 3, in <module>
# Copyright © 2011 Pierre Raybaut
File "D:\program oppinet\pyoppinet\helper\UnitInfo.py", line 2, in <module>
File "D:\program oppinet\pyoppinet\C_API\converter.py", line 26, in <module>
File "D:\program oppinet\pyoppinet\C_API\converter.py", line 18, inswig_import_helper
ImportError: No module named _converter
I believe that the error is caused by the setting in spyder, maybe in tools or something.
Could I change some setting in spyder to fix this problem?

Categories