<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: AMITH KUMAR S</title>
    <description>The latest articles on DEV Community by AMITH KUMAR S (@titanexasaur).</description>
    <link>https://dev.to/titanexasaur</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1455826%2Fbb9cff35-bb4d-41e4-b0c0-62bbc7eefee1.png</url>
      <title>DEV Community: AMITH KUMAR S</title>
      <link>https://dev.to/titanexasaur</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/titanexasaur"/>
    <language>en</language>
    <item>
      <title>Help with flask, almost done. Almost!!</title>
      <dc:creator>AMITH KUMAR S</dc:creator>
      <pubDate>Mon, 29 Apr 2024 06:26:29 +0000</pubDate>
      <link>https://dev.to/titanexasaur/help-with-flask-almost-done-almost-4lm0</link>
      <guid>https://dev.to/titanexasaur/help-with-flask-almost-done-almost-4lm0</guid>
      <description>&lt;p&gt;Hello, I have been working on a project which has not let me sleep for a while now&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import subprocess
import sys
from imutils.video import VideoStream
import imutils
import numpy as np
import cv2
import pickle
import time
from flask import *
import os, sys

app = Flask(__name__)

# Load face detector, face embedding model, recognizer, and label encoder
protoPath = "face_detector/deploy.prototxt"
modelPath = "face_detector/res10_300x300_ssd_iter_140000.caffemodel"
detector = cv2.dnn.readNetFromCaffe(protoPath, modelPath)

embedder = cv2.dnn.readNetFromTorch("face_detector/openface_nn4.small2.v1.t7")

recognizer = pickle.loads(open("output/recognizer.pickle", "rb").read())
le = pickle.loads(open("output/le.pickle", "rb").read())

# Global variable to store the current class label
current_label = ""
entered_username = ""
username_printed = False

def generate_frames(entered_username):
    global current_label, username_printed
    vs = VideoStream(src=0).start()
    time.sleep(2.0)
    last_print_time = time.time()

    while True:
        frame = vs.read()
        frame = imutils.resize(frame, width=600)
        (h, w) = frame.shape[:2]

        imageBlob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0, (300, 300),
                                          (104.0, 177.0, 123.0), swapRB=False, crop=False)

        detector.setInput(imageBlob)
        detections = detector.forward()

        for i in range(0, detections.shape[2]):
            confidence = detections[0, 0, i, 2]

            if confidence &amp;gt; 0.5:
                box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
                (startX, startY, endX, endY) = box.astype("int")

                face = frame[startY:endY, startX:endX]
                (fH, fW) = face.shape[:2]

                if fW &amp;lt; 20 or fH &amp;lt; 20:
                    continue

                faceBlob = cv2.dnn.blobFromImage(face, 1.0 / 255, (96, 96), (0, 0, 0), swapRB=True, crop=False)
                embedder.setInput(faceBlob)
                vec = embedder.forward()

                preds = recognizer.predict_proba(vec)[0]
                j = np.argmax(preds)
                proba = preds[j]
                name = le.classes_[j]

                current_label = name  # Update the global variable with the current class label

                text = "{}: {:.2f}%".format(name, proba * 100)
                y = startY - 10 if startY - 10 &amp;gt; 10 else startY + 10
                cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 0, 255), 2)
                cv2.putText(frame, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)

                # Check if the username has been entered and not printed yet
                if entered_username and not username_printed:
                    print("Username entered:", entered_username)
                    username_printed = True

        ret, buffer = cv2.imencode('.jpg', frame)
        frame = buffer.tobytes()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

        # Check if 10 seconds have passed since the last print
        if time.time() - last_print_time &amp;gt;= 5:
            print("Current label:", current_label)
            last_print_time = time.time()

            print("entered username : ", entered_username)

            if current_label == entered_username:
                vs.stop()
                print('redirecting....')
                index()  # Call index function directly

@app.route('/')
def index():
    return render_template('login.html', current_label=current_label)

@app.route('/video_feed')
def video_feed():
    global entered_username
    return Response(generate_frames(entered_username), mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/setUsername', methods=['POST'])
def set_username():
    global entered_username
    entered_username = request.json.get('username')
    return redirect('/home')

@app.route('/home')
def home():
    return render_template('index.html')

if __name__=='__main__':
    app.run(debug=True)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;this is the source code, here's the flow of the program,&lt;br&gt;
a. I will execute the code that starts the server&lt;br&gt;
b. I will enter the username on the webpage and click submit&lt;br&gt;
c. face recognition module will identify the face from live camera feed and return class label&lt;br&gt;
d. if the entered username and class label are same, then I want to redirect to index.html&lt;/p&gt;

&lt;p&gt;the first three steps are working well and fine, last step I am getting the following error,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;127.0.0.1 - - [29/Apr/2024 11:55:44] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [29/Apr/2024 11:55:44] "GET /static/style_face.css HTTP/1.1" 304 -
127.0.0.1 - - [29/Apr/2024 11:55:44] "GET /static/img_2.webp HTTP/1.1" 304 -
127.0.0.1 - - [29/Apr/2024 11:55:47] "POST /setUsername HTTP/1.1" 302 -
127.0.0.1 - - [29/Apr/2024 11:55:47] "GET /home HTTP/1.1" 200 -
Username entered: kumar
127.0.0.1 - - [29/Apr/2024 11:55:49] "GET /video_feed HTTP/1.1" 200 -
Current label: kumar
entered username :  kumar
redirecting....
Debugging middleware caught exception in streamed response at a point where response headers were already sent.
Traceback (most recent call last):
  File "/home/kumar/anaconda3/envs/main/lib/python3.8/site-packages/werkzeug/wsgi.py", line 256, in __next__
    return self._next()
  File "/home/kumar/anaconda3/envs/main/lib/python3.8/site-packages/werkzeug/wrappers/response.py", line 32, in _iter_encoded
    for item in iterable:
  File "/home/kumar/Downloads/Multi disease prediction(update 21-03-2024)/new_app_2.py", line 95, in generate_frames
    index()  # Call index function directly
  File "/home/kumar/Downloads/Multi disease prediction(update 21-03-2024)/new_app_2.py", line 99, in index
    return render_template('login.html', current_label=current_label)
  File "/home/kumar/anaconda3/envs/main/lib/python3.8/site-packages/flask/templating.py", line 148, in render_template
    app = current_app._get_current_object()  # type: ignore[attr-defined]
  File "/home/kumar/anaconda3/envs/main/lib/python3.8/site-packages/werkzeug/local.py", line 508, in _get_current_object
    raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Can someone please help me out here?&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
