How to load images in django reportlab - django

hi i am trying to load a image onto a pdf with reportlab but i keep getting
OSError at /view_checklist_print/1
Cannot open resource "check_box_outline_blank.svg"
This is my test
i21 = False
This is my view
def checklist_report(reques):
buffer = io.BytesIO()
c = canvas.Canvas(buffer, pagesize=(8.5 * inch, 11 * inch))
def checkboxgenerator(a, b, checkdata):
checked = 'static/images/check_box_FILL.svg'
unchecked = 'static/images/check_box_outline_blank.svg'
x_start = a
y_start = b
blankbox = c.drawImage(unchecked, x_start, y_start, width=120, preserveAspectRatio=True, mask='auto')
checkedbox = c.drawImage(checked, x_start, y_start, width=120, preserveAspectRatio=True, mask='auto')
if checkdata == False:
return blankbox
else:
return checkedbox
checkboxgenerator(20, 300, i21)
c.showPage()
c.save()
buffer.seek(0)
return FileResponse(buffer, as_attachment=False, filename=test.pdf')
Please can you help me load the image correctly

You should put your SVG files in the same directory as your current python file or use the exact path to the SVG file path.

Related

loading data using tf.from_tensor_slices yields OperatorNotAllowedInGraphError

I am trying to use tf.data pipeline to get finer control over loading image data but I receive the following error which I think is because of usage of list comprehension. My Code looks like this:
def load_files(data_dir: str, val_split=0.2):
assert len(os.listdir(os.path.join(data_dir + 'images/'))) == \
len(os.listdir(os.path.join(data_dir, 'ground_truth/'))), print("No. of image files != No. of gt files")
image_count = len(os.listdir(os.path.join(data_dir + 'images/')))
files = os.listdir(os.path.join(data_dir + 'images/'))
image_files = [os.path.join(data_dir + 'images/', file) for file in files]
image_files = np.array(image_files)
ds = tf.data.Dataset.from_tensor_slices(files)
ds = ds.map(process_data)
# train_ds = ds.skip(int(val_split * image_count))
# val_ds = ds.take(int(val_split * image_count))
return ds
def process_data(file_path):
image, = tf.io.read_file(file_path)
image = tf.io.decode_jpeg(image, channels=3)
label = tf.strings.split(file_path)
label = tf.io.decode_png(label, channels=0, dtype=tf.uint8)
return image, label
some_dir = "../../../TuSimple_lane_detection/"
img_dir = some_dir + "images/"
mask_dir = some_dir + "ground_truth/"
data_train = load_files(some_dir)
for f in data_train.take(5):
print(f.numpy())
The error looks like this:
File "E:\Datasets\KITTI_3D_Object_detection\venv\PycharmProjects\lib\site-packages\tensorflow\python\eager\function.py", line 3210, in _get_concrete_function_garbage_collected
graph_function, _ = self._maybe_define_function(args, kwargs)
File "E:\Datasets\KITTI_3D_Object_detection\venv\PycharmProjects\lib\site-packages\tensorflow\python\eager\function.py", line 3557, in _maybe_define_function
graph_function = self._create_graph_function(args, kwargs)
File "E:\Datasets\KITTI_3D_Object_detection\venv\PycharmProjects\lib\site-packages\tensorflow\python\eager\function.py", line 3392, in _create_graph_function
func_graph_module.func_graph_from_py_func(
File "E:\Datasets\KITTI_3D_Object_detection\venv\PycharmProjects\lib\site-packages\tensorflow\python\framework\func_graph.py", line 1143, in func_graph_from_py_func
func_outputs = python_func(*func_args, **func_kwargs)
File "E:\Datasets\KITTI_3D_Object_detection\venv\PycharmProjects\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 4510, in wrapped_fn
ret = wrapper_helper(*args)
File "E:\Datasets\KITTI_3D_Object_detection\venv\PycharmProjects\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 4440, in wrapper_helper
ret = autograph.tf_convert(self._func, ag_ctx)(*nested_args)
File "E:\Datasets\KITTI_3D_Object_detection\venv\PycharmProjects\lib\site-packages\tensorflow\python\autograph\impl\api.py", line 699, in wrapper
raise e.ag_error_metadata.to_exception(e)
tensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError: in user code:
File "E:/Datasets/KITTI_3D_Object_detection/KITTI_2D/EndToEndLaneDetection/Dataloader.py", line 21, in process_data *
image, = tf.io.read_file(file_path)
OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed in Graph execution. Use Eager execution or decorate this function with #tf.function.
I did not have the problem when I was working with TF1.12 before, when I shifted o TF 2.3 I am encountering this error.

django filter data and make union of all data points to assignt to a new data

My model is as follows
class Drawing(models.Model):
drawingJSONText = models.TextField(null=True)
project = models.CharField(max_length=250)
Sample data saved in drawingJSONText field is as below
{"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]}
I am trying to write a view file where the data is filtered based on project field and all the resulting queryset of drawingJSONText field are made into one data
def load(request):
""" Function to load the drawing with drawingID if it exists."""
try:
filterdata = Drawing.objects.filter(project=1)
ids = filterdata.values_list('pk', flat=True)
length = len(ids)
print(list[ids])
print(len(list(ids)))
drawingJSONData = dict()
drawingJSONData = {'points': [], 'lines': []}
for val in ids:
if length >= 0:
continue
drawingJSONData1 = json.loads(Drawing.objects.get(id=ids[val]).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]
length -= 1
#print(drawingJSONData)
drawingJSONData = json.dumps(drawingJSONData)
context = {
"loadIntoJavascript": True,
"JSONData": drawingJSONData
}
# Editing response headers and returning the same
response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context))
return response
I runs without error but it shows a blank screen
i dont think the for function is working
any suggestions on how to rectify
I think you may want
for id_val in ids:
drawingJSONData1 = json.loads(Drawing.objects.get(id=id_val).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]

\u0000 cannot be converted to text in django/postgreSQl

i have a project with django .on the host when i want to upload an image sometime error occurred(problem with specific images)! the below show how i resize uploaded images:
def save_files_to_media(request, is_public=False, klass=None, conversation=None):
from apps.file.models import File
fs = FileSystemStorage()
file_items = {}
for data_item in request.data:
file_match = re.search('^fileToUpload\[(\d+)\]$', data_item)
if file_match and file_match.groups():
item_index = file_match.groups()[0]
if item_index not in file_items:
file_items[item_index] = {}
file_items[item_index]['file_to_upload'] = request.data[data_item]
else:
optimize_match = re.search('^optimizeType\[(\d+)\]$', data_item)
if optimize_match and optimize_match.groups():
item_index = optimize_match.groups()[0]
if item_index not in file_items:
file_items[item_index] = {}
file_items[item_index]['optimize_type'] = request.data[data_item]
files = []
for file_item_key in file_items:
input_file = file_items[file_item_key]['file_to_upload']
# TODO: checking validation. if input_file.name is not exist
optimize_type = file_items[file_item_key].get('optimize_type')
file_uuid = str(uuid4())
if is_public:
orig_filename, file_ext = splitext(basename(input_file.name))
directory_name = join(settings.MEDIA_ROOT, file_uuid)
filename = file_uuid + file_ext
else:
directory_name = join(settings.MEDIA_ROOT, file_uuid)
mkdir(directory_name)
filename = input_file.name
filepath = join(directory_name, filename)
fs.save(filepath, input_file)
is_optimized = False
if optimize_type == 'image':
is_success, filepath = image_optimizer(filepath)
filename = basename(filepath)
is_optimized = is_success
file_obj = File(
orig_name=filename,
uuid=file_uuid,
md5sum=get_md5sum(filepath),
filesize=get_filesize(filepath),
meta=get_meta_info(filepath),
is_optimized=is_optimized,
creator=request.user
)
if is_public:
file_obj.is_public = True
else:
file_obj.klass = klass
file_obj.conversation = conversation
file_obj.save()
files.append(file_obj)
return files
here is the error i got with some images:
unsupported Unicode escape sequence
LINE 1: ..., 'ada90ead20f7994837dced344266cc51', 145216, '', '{"FileTyp...
^
DETAIL: \u0000 cannot be converted to text.
CONTEXT: JSON data, line 1: ...ecTimeDigitized": 506779, "MakerNoteUnknownText":
its funny that in my local but not in host. for more information i must tell you guys my postgreSQL version is 11.3 and host postgreSQl is 9.5.17 . where you think is problem? as error it's seems for postgreSQL. thank you

Unexpected Output In Python While Using MoviePy

Hi i added a simple GUI in this script
A python script to automatically summarize soccer videos based on the crowd's reactions
The GUI script is the following
from Tkinter import *
from tkFileDialog import askopenfilename
from soccer_reacts import video_edit
class MyFrame(Frame):
def __init__(self):
master = Tk()
Label(master, text="Please Insert Video Path With Browse", width=30).grid(row=0)
Frame.__init__(self)
self.master.title("Video Editor")
self.master.geometry('{}x{}'.format(300, 200))
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=15)
self.button.grid(row=1, column=0, sticky=W)
self.button2 = Button(self, text="Start", command=self.vid_reactions, width=15)
self.button2.grid(row=2, column=0, sticky=W)
def load_file(self):
fname = askopenfilename(filetypes=(("MP4 files", "*.mp4"),("All files", "*.*") ))
if fname:
self.fname = fname
def vid_reactions(self):
print("[*]Starting operation")
print("[*]File : "+self.fname)
video_edit(self.fname)
print("[*]Operation Finished")
if __name__ == "__main__":
MyFrame().mainloop()
End this is the new code of soccer cuts
import numpy as np # for numerical operations
from moviepy.editor import VideoFileClip, concatenate
def video_edit(file_name):
clip = VideoFileClip(file_name)
cut = lambda i: clip.audio.subclip(i,i+1).to_soundarray(fps=22000)
volume = lambda array: np.sqrt(((1.0*array)**2).mean())
volumes = [volume(cut(i)) for i in range(0,int(clip.audio.duration-2))]
averaged_volumes = np.array([sum(volumes[i:i+10])/10
for i in range(len(volumes)-10)])
increases = np.diff(averaged_volumes)[:-1]>=0
decreases = np.diff(averaged_volumes)[1:]<=0
peaks_times = (increases * decreases).nonzero()[0]
peaks_vols = averaged_volumes[peaks_times]
peaks_times = peaks_times[peaks_vols>np.percentile(peaks_vols,90)]
final_times=[peaks_times[0]]
for t in peaks_times:
if (t - final_times[-1]) < 60:
if averaged_volumes[t] > averaged_volumes[final_times[-1]]:
final_times[-1] = t
else:
final_times.append(t)
final = concatenate([clip.subclip(max(t-5,0),min(t+5, clip.duration))
for t in final_times])
final.to_videofile(file_name) # low quality is the default
When i run the new code, the output is a mp4 file, with the sound of the match
but with no video. I ve checked all the changes i made and i cannot find something wrong. Can anyone help?
I do not why but changing last line from
final.to_videofile(file_name)
to final.write_videofile('The result.mp4')
was a solution

django - HTML to PDF in Indian languages with pisa

I'm converting a HTML file into PDF in Django using Pisa. It is working when the content is only in English. But here the content will be in English and five other Indian languages(Tamil, Hindi, Telugu, Malayalam, and Kannada). I have given my code below.
views.py
def render_to_pdf1(template_src, context_dict):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode('UTF-8')), result)
return result.getvalue()
def print_pdf(request):
message = Message.objects.get(id = 1)
html_table_string = ''
html_table_string += '%s' % message.english
html_table_string += '%s' % message.tamil
html_table_string += '%s' % message.hindi
html_table_string += '%s' % message.telugu
html_table_string += '%s' % message.kannada
html_table_string += '%s' % message.malayalam
fileread = str(settings.TEMPLATE_DIRS[0])+str('/base_file.html')
fr = open(fileread, "r").read()
fr = fr.replace('message_content', html_table_string)
result = StringIO.StringIO()
filewrite = str(settings.TEMPLATE_DIRS[0]) + str('/temp_file.html')
empty = ""
fw = open(filewrite, 'w')
fw.write(empty)
fw.write(fr)
fw.close()
pdf_contents = render_to_pdf1('temp_file.html',result)
file_to_be_saved = ContentFile(pdf_contents)
name = (str(request.user.email) + ".pdf").replace("#", '')
pdf = Pdf.objects.create(name = name, user = request.user, created_by = request.user)
pdf.name.save(name ,file_to_be_saved)
file_path = Pdf.objects.get(user = request.user).name
pdf_file = str(file_path).split("media")[1]
return HttpResponseRedirect('/site_media' + pdf_file)
Here what I'm doing is:
Having a base template base_file.html.
Getting the message object by ID (ID will be dynamically supplied).
Then replacing the message_content with current content.
Writing it in a file temp_file.html.
Converting temp_file.html into a PDF file.
The converted PDF will be containing the message in English, Tamil, Hindi, Telugu, Kannada, and Malayalam. But I couldn't write the other language contents in the HTML file and couldn't convert it. The error I'm getting is 'ascii' codec can't encode characters in position 1066-1075: ordinal not in range(128) and occurs in the line fw.write(fr).
So how can I achieve this? I want to print the PDF file with content in all these languages.