How to run python function in laravel with symfony process?

Question:

I have a python function which returns string data, code runs fine after run

import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="",
    database="db_absensi"
)

mycursor = mydb.cursor() 


def example():
    mycursor.execute("SELECT * FROM examples)
    data = mycursor.fetchall()
 
    return data

this is my symfony code

 public function test()
    {
        $process = new Process(['python ../../../app/data.py']);
        $process->setTimeout(3600);
        $process->run();

        if(!$process->isSuccessful())
        {
            throw new ProcessFailedException($process);
        }

        dd ($process->getOutput());


        return view("testView");
    }

and also I have another function that does not return data but a function, I plan to call this function with a procedure like in flask

def face_recognition():  # generate frame by frame from camera
    def draw_boundary(img, classifier, scaleFactor, minNeighbors, color, text, clf):
        gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        features = classifier.detectMultiScale(gray_image, scaleFactor, minNeighbors)
 
        global justscanned
        global pause_cnt
 
        pause_cnt += 1
 
        coords = []
 
        for (x, y, w, h) in features:
            cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
            id, pred = clf.predict(gray_image[y:y + h, x:x + w])
            confidence = int(100 * (1 - pred / 300))
 
            if confidence > 70 and not justscanned:
                global cnt
                cnt += 1
 
                n = (100 / 30) * cnt
                w_filled = (cnt / 30) * w
 
                cv2.putText(img, str(int(n))+' %', (x + 20, y + h + 28), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,255,255), 2, cv2.LINE_AA)
 
                cv2.rectangle(img, (x, y + h + 40), (x + w, y + h + 50), color, 2)
                cv2.rectangle(img, (x, y + h + 40), (x + int(w_filled), y + h + 50), (255,255,255), cv2.FILLED)
 
                mycursor.execute("SELECT a.img_person, b.nama, b.kelas, b.tanggal_lahir "
                                 " FROM images a "
                                 " LEFT JOIN data_person b ON a.img_person = b.id_master "
                                 " WHERE img_id = " + str(id))
                row = mycursor.fetchone()
                pnbr = row[0]
                pname = row[1]
                pkelas = row[2]
 
                if int(cnt) == 30:
                    cnt = 0
 
                    mycursor.execute("INSERT INTO attendance_datamaster (attendance_date, attendance_person) VALUES('"+str(date.today())+"', '" + pnbr + "')")
                    mydb.commit()
 
                    cv2.putText(img, pname + ' | ' + pkelas, (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,255,255), 2, cv2.LINE_AA)
                    time.sleep(4)
                    # speech.say(pname + "successfully processed")
                    # speech.runAndWait()

                    justscanned = True
                    pause_cnt = 0
 
            else:
                if not justscanned:
                    cv2.putText(img, 'UNKNOWN', (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2, cv2.LINE_AA)
                else:
                    cv2.putText(img, ' ', (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2,cv2.LINE_AA)
 
                if pause_cnt > 80:
                    justscanned = False
 
            coords = [x, y, w, h]
        return coords
 
    def recognize(img, clf, faceCascade):
        coords = draw_boundary(img, faceCascade, 1.1, 10, (255, 255, 255), "Face", clf)
        return img
 
    faceCascade = cv2.CascadeClassifier("resources/haarcascade_frontalface_default.xml")
    clf = cv2.face.LBPHFaceRecognizer_create()
    clf.read("classifier.xml")
 
    wCam, hCam = 400, 400
 
    cap = cv2.VideoCapture(0)
    cap.set(3, wCam)
    cap.set(4, hCam)
 
    while True:
        ret, img = cap.read()
        img = recognize(img, clf, faceCascade)
 
        frame = cv2.imencode('.jpg', img)[1].tobytes()
        yield (b'--framern'
               b'Content-Type: image/jpegrnrn' + frame + b'rnrn')
 
        key = cv2.waitKey(1)
        if key == 27:
            break

def video_feed(): 
    return Response(face_recognition(), mimetype='multipart/x-mixed-replace; boundary=frame')

I wanna put this function on src attribute of image (opencv function).
This is what I usually do in flask

<div class="col-md-8 " style="margin-top: 10%;">
    <img src="{{ url_for('video_feed') }}" width="100%" class="img-thumbnail">
</div>

Is there a similar way, or a way that is possible to run a python function that doesn’t return string data inside laravel environment?

Asked By: T Maulana A.L

||

Answers:

For your first python script I would suggest you to simply recreate that mysql select within php.

For def video_feed: Like Christoph mentioned in the comments, this return value looks like a http response. So you mixing something up. Probably simply return face_recognition() as json and use it with python process or start your python program as a http server and send a http request from laravel to python.

And to use symphony/process you better use multiple arguments and full path like new Process(['/usr/bin/python3.6', '/var/www/app/data.py']);.

Answered By: PKeidel