Home > Blockchain >  Why does the flask read another file?
Why does the flask read another file?

Time:11-24

├── app.py
├── static
│   -
├── templates
│   
└── utils
    ├── __init__.py
    ├── __pycache__
    │   ├── __init__.cpython-36.pyc
    │  
    ├── __dataset__
          ├── __pycache__
    │         ├── __init__.cpython-36.pyc
    │         ├── fer.cpython-36.pyc
    │     ├── _init_.py
    │     └── fer.cpython-36.py
    ├── _init_.py    

├── camera.py
├── model.py
├── PythonApplication1.py

When I run the python -m flask run with

import PythonApplication1 as py1

it runs PythonApplication1 first and then it gives error msg

While importing 'app', an ImportError was raised.

I don't know why PythonApplication1 goes first, although I did FLASK_APP = app.py.

Also I don't know what to do with the error. Pls help me

app.py

from flask import Flask, render_template, Response
from flask_bootstrap import Bootstrap
from camera import VideoCamera
import pymysql
import PythonApplication1 as py1

app = Flask(__name__)
Bootstrap(app)

if __name__ == '__main__':
    app.run(host='127.0.0.1',port=5000, debug=True)

PythonApplication1.py

import sounddevice as sd
from numpy import linalg as LA
import numpy as np

duration = 20  

global cnt
global check_cnt
cnt = 0
check_cnt = 0

def print_sound(indata, outdata, frames, time, status):
    volume_norm = np.linalg.norm(indata)*10
        
a = int(volume_norm)
global cnt
global check_cnt
    
if a <= 28: 
    cnt = cnt   1
            
if cnt == 300: 
      check_cnt  = 1
      print ("You are too quiet!","Now you're checked", check_cnt, "times");
       cnt = 0; 
    
with sd.Stream(callback=print_sound):
    sd.sleep(duration * 1000)

init.py

import os
import utils.datasets.fer
import app

camera.py

import cv2
from model import FacialExpressionModel
import sys
import numpy as np

facec = cv2.CascadeClassifier('Haarcascades/haarcascade_frontalface_default.xml')
model = FacialExpressionModel("model.json", "model_weights.h5")
font = cv2.FONT_HERSHEY_SIMPLEX

class VideoCamera(object):
    def __init__(self):
        #self.video = cv2.VideoCapture('facial_exp.mkv')
        self.video = cv2.VideoCapture(0)

    def __del__(self):
        self.video.release()

    # returns camera frames along with bounding boxes and predictions
    def get_frame(self):
        _, fr = self.video.read()
        gray_fr = cv2.cvtColor(fr, cv2.COLOR_BGR2GRAY)
        faces = facec.detectMultiScale(gray_fr, 1.3, 5)

        for (x, y, w, h) in faces:
            fc = gray_fr[y:y h, x:x w]

            roi = cv2.resize(fc, (48, 48))
            pred = model.predict_emotion(roi[np.newaxis, :, :, np.newaxis])

            cv2.putText(fr, pred, (x, y), font, 1, (255, 255, 0), 2)
            cv2.rectangle(fr,(x,y),(x w,y h),(255,0,0),2)

        _, jpeg = cv2.imencode('.jpg', fr)
        return jpeg.tobytes()

model.py

from tensorflow.keras.models import model_from_json
from tensorflow.python.keras.backend import set_session
import numpy as np
import tensorflow as tf

config = tf.compat.v1.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.15
session = tf.compat.v1.Session(config=config)
set_session(session)


class FacialExpressionModel(object):

    EMOTIONS_LIST = ["Angry", "Disgust",
                     "Fear", "Happy",
                     "Neutral", "Sad",
                     "Surprise"]

    def __init__(self, model_json_file, model_weights_file):
        # load model from JSON file
        with open(model_json_file, "r") as json_file:
            loaded_model_json = json_file.read()
            self.loaded_model = model_from_json(loaded_model_json)

        # load weights into the new model
        self.loaded_model.load_weights(model_weights_file)
        #self.loaded_model.compile()
        #self.loaded_model._make_predict_function()

    def predict_emotion(self, img):
        global session
        set_session(session)
        self.preds = self.loaded_model.predict(img)
        return FacialExpressionModel.EMOTIONS_LIST[np.argmax(self.preds)]

I don't think it's a error msg, I still dont get why PythonApplication1 pulls out first

the Terminal tells me this

python -m flask run 
 * Environment: production
   WARNING: This is a development server. Do not use it in a 
production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
2021-11-23 21:54:51.825585: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found
2021-11-23 21:54:51.837461: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
2021-11-23 21:54:55.404593: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with 
oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2021-11-23 21:54:55.427262: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library/cuda_driver.cc:269] failed call to cuInit: UNKNOWN ERROR (303)3)                                                           /cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: DESKTOP-VTL81IN
2021-11-23 21:54:55.457096: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: DESKTOP-VTL81IN/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: DESKTOP-VTL81IN
2021-11-23 21:54:55.464063: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: DESKTOP-VTL81IN
You are too quiet! Now you're checked 1 times
You are too quiet! Now you're checked 2 times
 * Running on http://127.0.0.1:5000/ (Press CTRL C to quit)  

enter image description here

this is my structure

CodePudding user response:

If you dont want import PythonApplication1 as py1 to go first, then put that import statement at the last line in app.py.

CodePudding user response:

When you import a module in Python, everything in that module is run at the time of import. For most cases modules intended to be imported. only contain classes, functions and maybe a handful of variables.

As everything in your PythonApplication module is at the top level, it is running on import. This is the purpose for the if __name__ == "__main__": guard in your app file.

I imagine what you need to do is wrap the code you have in PythonApplication into a function that can be imported, then use that from app.py.

CodePudding user response:

In app.py

from PythonApplication1 import * as py1

  • Related