Live Stream text to HTML tamplets - django

I have a function at the back-end in Django that calculate and return frames speed of a video given to opencv.videoCapture()`. The type of the speed is float.
class video_feed(object):
def __init__(self, pathVideo):
self.cap = cv.VideoCapture(pathVideo)
#some code .....
def __del__(self):
self.cap.release()
def get_frames(self):
#some code ...
return speed_list
This method keep calling the method while the video is working:
def gen_speed(video_feed):
print('this is spped generation method')
while True:
speed = video_feed.get_frames()
yield(speed)
#gzip.gzip_page
def speed_frame(request):
try:
pathVideo = "video_detection/statics/rl4_pb8-7.mp4"
cam = model.video_feed(pathVideo)
#return StreamingHttpResponse(model.gen_test(cam),content_type="text/csv")
return HttpResponse({'speed':cam.get_frames()})
except:
print("speed_frame not working !!!!!!!!!!!!!!!!!!!!!!!!")
But this code doesn't work. I need a way to make the speed stream to my HTML page so I can use it in a chartjs.
Streaming video using OpenCV is woking just fine but when I change the type to float it doesn't work.

I finally found a better way. Which is using Django channels to stream data in JSON format.

Related

Django Validate Image or File With A Form Inside a Form

Hello I'm having trouble here with multiple image with same field.
As far as I know in django tutorial they telling this.
for f in request.FILES.getlist('files'):
# do something (validate here maybe)
in which I don't quite get it. Like do i do manual validation? If so why?
Anyway there is another approach they give
files = forms.FileField(widget=ClearableFileInput(attrs={'multiple': True})
This one does not work in the way I want. It's self.cleaned_data['files'] only gives one output (There is a similar problem here) and django/multiupload was having a bug on my experience and sadly it was too slow to fix :(.
What I want was to validate each file and give errors to each via ImageField because I like it was validating a file versus I code it myself.
Thus I made a prototype code.
forms.py
class ImageForm(forms.Form):
# validate each image here
image = forms.ImageField()
class BaseForm(forms.Form):
# first form
ping = forms.CharField()
#images = SomeThingMultipleFileField that will raise multiple errors each validate image.
# since no option I decided to do that. below.
# so for decoration that images is required.
images = forms.ImageField()
def handle(self, request, *args, **kwargs):
#custom function
image_list = []
errors = []
# validate each image in images via another form
# if there is errors e.g this field is required will be append to errors = []
for image in request.FILES.getlist('images'):
data = ImageForm(image)
if data.is_valid():
image_list.append(data.cleaned_data['image'])
else:
errors.append(data.errors)
if errors:
# raise errors
# return the data
views.py
def base(request):
# this is an api
# expected input should be from the code or format
# {'ping': 'test', 'images': 1.jpg, 'images': 2.jpg}
# This is not the actual view code.
data = forms.BaseForm(request.POST, request.FILES)
if data.is_valid():
value = data.handle(request)
return JSONResponse({'data': value})
return JSONResponse({'errors': data.errors})
Not elegant to be honest but having trouble now and no more options I can think off but that.
The problem in my code is that
data = ImageForm(image)
does not reading the file thus image_list is always empty
So anyone can help me here?. Im stuck
Any better approach?
I wonder also for a general error like if one image is not valid it triggers like {'files': 'One of the images is not valid.'}
so far, I tested again so my bad
it seems it requires the format of data, files in ordinary forms.
in order to do so.
forms.py
... # previous code
# data = ImageForm(image) , old code
data = ImageForm({}, {'image': image})
in this way,it fills up the default QueryDict: {}, MultiValueDict in the args
Number 3 can be answered.
instead of
# previous code
else:
errors.append(error)
now should be
raise ValidationError(_('Your error'))
Any Better approach?
Not much I can think off sadly. So anyone stumble here. feel free to comment. Much appreciated for the help.

Can I do some preprocessing on image and use it without save changes?

Recently I wrote a code that reads an image from an object storage. Then I do some simple image processing on the image. but I don't want to save changes on the main image, also I don't want to copy image because of performance reasons. I just want to send manipulated image to a vies function in django in order to open it as a data file.
is it any way to do this job?
this is my function's schema.
def watermark_image(image_name):
# do some image processing on input image
# cv2.imwrite(image_name, image)
return image
and this is a part of my function view:
if request.method == 'GET':
new_image = watermark_image(local_path + object_name)
# image_data = open(??? , "rb").read()
image_data = open(new_image , "rb").read()
return HttpResponse(image_data, content_type="image/png")
i don't know what should to wirte insetead of this line :
image_data = open(new_image , "rb").read()

How to convert an uploaded file (InMemoryUploadedFile) from pdf to jpeg in Django using wand?

I'm trying to convert a pdf file uploaded in Django to a jpg file. I would like to use the file directly in the InMemoryUploadedFile state.
I tried to use wand but without any success.
Here is the code I wrote:
from django.shortcuts import render
from wand.image import Image as wi
# Create your views here.
def readPDF(request):
context = {}
if request.method == 'POST':
uploaded_file = request.FILES['document']
if uploaded_file.content_type == 'application/pdf':
pdf = wi(filename=uploaded_file.name, resolution=300)
pdfImage = pdf.convert("jpeg")
return render(request, 'readPDF.html', {"pdf": pdfImage})
I tried different things like using uploaded_file.file or uploaded_file.name as the first argument for the wand image but without any success.`
I thank you in advance for your help!
Should be able to pass InMemoryUploadedFile directly to Wand's constructor.
uploaded_file = request.FILES['document']
if uploaded_file.content_type == 'application/pdf':
with wi(file=uploaded_file, resolution=300) as pdf:
# ...
However, I wouldn't recommend attempting to convert PDF pages to JPEGs in a HTTP request. Best to write the document to storage, and have a background worker manage the slow / unsafe tasks.

How to retrieve a .wav file through POST in django and store it in a data model?

I am learning VXML and Django. I am trying to find out how to cleanly retrieve a recording from some voice-xml (vxml) browser and pass it to the server side where I use django to further handle the passed information. Then I want to store the file somewhere in a .wav file to replay it later. I have the following code snippets:
In the VXML file:
<record name="recording" />
[here i record the recording]
<filled>
<submit next="/url/" method="post" namelist="recording"/>
</filled>
In the urls.py of django, I would have
url(r'^url$', view.index, name='index')
The views.index definition
def index(request):
_recording = [..retrieve .wav from request here]
_modelObject = ModelObject(recording= _recording)
_modelObject.save() #store recording in some database
return render(request, 'genericfile.xml', content_type='text/xml')
In the model.py I'd guess I would have a class like:
from django.db import model
class ModelObject(model.Models)
recording = [declare type of .wav file here]
How would I go about completing the steps in the [..] in a clean manner?
I didn't work with vxml before but look like you want to store both .xml format and .wav format.
So here is my solution in this case:
from django.db import model
class ModelObject(model.Models)
# Define a text filed or anything that can store long string
# of _recording var above.
recording = models.TextField()
def save(self, *args, **kwargs):
if self.recording:
# Convert vxml to wav and store to a file
pass
super(ModelObject, self).save(*args, **kwargs)
#property
def recording_wav(self):
if not self.recording:
return None
return 'path/to/file.wav'
Remember use post_delete signal to remove file.wav once an instance of ModelObject is deleted.

gobject.io_add_watch continuous callback from pyalsaaudio

I'm trying to create a small custom mixer that suits my needs, using python 2.7 and pyalsaaudio 0.7, but I'm stuck with events got from alsamixer when another program changes the volume values. I tried to understand how other mixers work (for example volti) and, as far as I understand, it should work as expected, but even if the method is similar, I still get a continuous loop of event response from io_add_watch. So, I suppose that I don't understand how io_add_watch works yet.
This is a small version of the code:
class MyMixer(gtk.Window):
def __init__(self):
super(MyMixer, self).__init__()
self.m = alsaaudio.Mixer(control='Headphone', id=1, cardindex=0)
""" here go the mixer widgets """
self.show_all()
fd, event = self.m.polldescriptors()[0]
self.watch = gobject.io_add_watch(fd, event, self.update)
def update(self, *args):
print 'changed'
""" here I update mixer widgets """
return True
mixer = MyMixer()
gtk.main()
What am I getting wrong?
When you get an event from the poll descriptors, you must call snd_mixer_handle_events().
pyalsaaudio has no mechanism for that.