예제 #1
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)

    db_session = init_db(app)

    scheduler = BackgroundScheduler()
    scheduler.start()
    scheduler.add_job(processing_timeout, 'interval', seconds=60)
    scheduler.add_job(old_files_removals, 'interval', hours=24)

    Path(app.config['PROCESSED_REQUESTS_FOLDER']).mkdir(parents=True,
                                                        exist_ok=True)
    Path(app.config['MODELS_FOLDER']).mkdir(parents=True, exist_ok=True)
    Path(app.config['UPLOAD_IMAGES_FOLDER']).mkdir(parents=True, exist_ok=True)

    Bootstrap(app)
    Dropzone(app)

    notification = db_session.query(Notification).first()
    if notification is not None:
        notification.last_notification = datetime.datetime(1970, 1, 1)
    else:
        notification = Notification(datetime.datetime(1970, 1, 1))
        db_session.add(notification)

    db_session.commit()

    jsglue = JSGlue()
    jsglue.init_app(app)

    from app.main import bp as main_bp
    app.register_blueprint(main_bp)

    return app
    def setUp(self):
        self.app = Flask(__name__)
        self.app.testing = True
        self.app.secret_key = 'for test'
        dropzone = Dropzone(self.app)  # noqa
        csrf = CSRFProtect(self.app)  # noqa

        self.dropzone = _Dropzone

        @self.app.route('/upload')
        def upload():
            pass

        @self.app.route('/')
        def index():
            return render_template_string('''
                    {{ dropzone.load_css() }}\n{{ dropzone.create(action_view='upload') }}
                    {{ dropzone.load_js() }}\n{{ dropzone.config() }}''')

        @self.app.route('/load')
        def load():
            return render_template_string('''
                            {{ dropzone.load() }}\n{{ dropzone.create(action_view='upload') }}'''
                                          )

        self.context = self.app.test_request_context()
        self.context.push()
        self.client = self.app.test_client()
예제 #3
0
def create_app():
    """Construct the core application."""
    app = Flask(__name__, template_folder="templates")
    dropzone = Dropzone(app)
    
    app.config['SECRET_KEY'] = 'supersecretkeygoeshere'

    app.config['DROPZONE_UPLOAD_MULTIPLE'] = True
    app.config['DROPZONE_ALLOWED_FILE_CUSTOM'] = True
    app.config['DROPZONE_ALLOWED_FILE_TYPE'] = 'image/*'
    # app.config['DROPZONE_REDIRECT_VIEW'] = 'results'

    # Uploads settings
    app.config['UPLOADED_PHOTOS_DEST'] = os.getcwd() + '/uploads'
    db.init_app(app)
    with app.app_context():
        from . import routes
        db.create_all()
    return app
예제 #4
0
    def __init__(self, staticfolder, workdir):
        self.app = Flask(__name__,
                         template_folder="templates",
                         static_url_path='/static',
                         static_folder=staticfolder)

        self.dropzone = Dropzone(self.app)
        self.workdir = workdir

        self.app.config.update(
            # Flask-Dropzone config:
            DROPZONE_ALLOWED_FILE_TYPE='image',
            DROPZONE_MAX_FILE_SIZE=3,
            DROPZONE_MAX_FILES=1,
            DROPZONE_DEFAULT_MESSAGE='Сбросьте файлы сюда, чтобы загрузить',
            DROPZONE_REDIRECT_VIEW="results",
            UPLOAD_FOLDER=staticfolder,
            STATIC_FOLDER=staticfolder,
            UPLOADED_PATH=staticfolder,
        )
예제 #5
0
    def __init__(self,
                 host: str = '0.0.0.0',
                 port: int = 8234,
                 debug: bool = False,
                 template_folder: str = None,
                 withFb4Common: bool = True,
                 explainTemplateLoading=False):
        '''
        constructor
        
        Args:
            host(str): flask host
            port(int): the port to use for http connections
            debug(bool): if True debugging should be switched on
            template_folder(str): the template folder to be used
            withFb4Common(bool): if True fb4common should be made available
            explainTemplateLoading(bool): if True the template loading should be explained/debugged
        '''
        self.debug = debug
        self.port = port
        self.host = host
        if template_folder is None:
            scriptdir = os.path.dirname(os.path.abspath(__file__))
            template_folder = scriptdir + '/../templates'

        self.app = Flask(__name__, template_folder=template_folder)
        global dropzone
        dropzone = Dropzone(self.app)
        # pimp up jinja2
        self.app.jinja_env.globals.update(isinstance=isinstance)
        self.auth = HTTPBasicAuth()
        self.baseUrl = ""
        self.bootstrap = Bootstrap(self.app)
        secretKey = os.urandom(32)
        for key, value in self.getAppConfig(
                explainTemplateLoading=explainTemplateLoading,
                secretKey=secretKey).items():
            self.app.config[key] = value
        if withFb4Common:
            self.fb4CommonBluePrint = Fb4CommonBluePrint(self.app, 'fb4common')
        self.csrf = CSRFProtect(self.app)
예제 #6
0
def create_app():
    app = Flask(__name__)

    app.secret_key = 'ursolobo'

    app.config['CACHE_TYPE'] = 'null'
    app.config['SECRET_KEY'] = 'ursolobo'
    app.config[
        'SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:' '@localhost:3306/lugares_a_ir'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    # Dropzone settings
    app.config['DROPZONE_UPLOAD_MULTIPLE'] = True
    app.config['DROPZONE_ALLOWED_FILE_CUSTOM'] = True
    app.config['DROPZONE_ALLOWED_FILE_TYPE'] = 'image/*'
    app.config['DROPZONE_REDIRECT_VIEW'] = 'results'

    dropzone = Dropzone(app)

    config_db(app)

    Migrate(app, app.db)

    login_manager = LoginManager()
    login_manager.login_view = 'bp_auth.login'
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.filter_by(id=user_id).first()

    from .auth import bp_auth
    app.register_blueprint(bp_auth)

    from .publicacoes import bp_publicacoes
    app.register_blueprint(bp_publicacoes)

    return app
예제 #7
0
def create_app():
    basedir = os.path.abspath(os.path.dirname(__file__))
    app = Flask(__name__)
    dropzone = Dropzone(app)

    app.config['SECRET_KEY'] = 'mysecret'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    app.config['UPLOADED_PATH'] = os.path.join(basedir, 'static/images')
    app.config['DROPZONE_ALLOWED_FILE_TYPE'] = 'image'
    app.config['DROPZONE_MAX_FILE_SIZE'] = 3
    app.config['DROPZONE_MAX_FILES'] = 1
    app.config['DROPZONE_IN_FORM'] = True
    app.config['DROPZONE_UPLOAD_ON_CLICK'] = True
    app.config['DROPZONE_UPLOAD_ACTION'] = 'main.handle_upload'
    app.config['DROPZONE_UPLOAD_BTN_ID'] = 'submit'

    db = SQLAlchemy(app)

    db.init_app(app)

    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    from .models import User

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(int(user_id))

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app
예제 #8
0
def CreateWallApp():
    app = WallApp(static_folder='assets', static_url_path='/assets')
    app.config.from_object(__name__ + '.ConfigClass')

    try:
        app.config.from_object('local_settings')
    except:
        pass

    # Use for Frontend debug
    # CORS(app, resources={r"/api/*": {"origins": "*"}})

    Compress(app)
    Cache(app)
    babel = Babel(app)
    login = LoginManager(app)

    def redirect_dest(fallback):
        dest = request.args.get('next')
        try:
            dest_url = url_for(dest)
        except:
            return redirect(fallback)
        return redirect(dest_url)

    @login.unauthorized_handler
    def handle_needs_login():
        flash("You have to be logged in to access this page.")
        return redirect(url_for('login', next=request.endpoint))

    @app.route("/login", methods=["GET", "POST"])
    def login():
        if request.method == 'POST':
            username = request.form['username']
            password = request.form['password']

            user = User.query.filter(or_(User.username == username, User.email == username)).first()
            if user is None or not user.check_password(password):
                flash("Sorry, but you could not log in.")
                redirect(url_for('home_page'))
            else:
                next = request.form['next']
                login_user(user, remember=True)
                return redirect(next)
        else:
            next = request.args.get('next')
            return render_template("login.html", next=next)

    login.login_view = 'login'

    @babel.localeselector
    def get_locale():
        return 'ru'

    app.dropzone = Dropzone(app)
    app.photos = UploadSet('photos', IMAGES)
    configure_uploads(app, app.photos)
    patch_request_class(app)  # set maximum file size, default is 16MB

    @app.template_filter('data_fmt')
    def data_fmt(filename):
        datatypes = {'image': 'gif,ico,jpe,jpeg,jpg,png,svg,webp'}

        t = 'unknown'
        for type, exts in datatypes.items():
            if filename.split('.')[-1] in exts:
                t = type
        return t

    @app.template_filter('icon_fmt')
    def icon_fmt(filename):
        icontypes = {'fa-picture-o': 'gif,ico,jpe,jpeg,jpg,png,svg,webp'}

        i = 'fa-file-o'
        for icon, exts in icontypes.items():
            if filename.split('.')[-1] in exts:
                i = icon
        return i

    @app.route('/')
    def home_page():
        users = db.session.query(func.count(User.id)).scalar()
        files = db.session.query(func.count(File.id)).scalar()
        classes = db.session.query(func.count(ObjectClass.id)).scalar()
        marked = db.session.query(File).filter(File.processed == True).count()
        is_logedin = current_user.is_authenticated
        return render_template("index.html", marked=str(marked), classes=str(classes), files=str(files),
                               users=str(users), is_logedin=is_logedin)

    @app.route('/images_page')
    @login_required
    def images_page():
        return render_template('images_page.html')

    @app.route("/logout")
    @login_required
    def logout():
        logout_user()
        return redirect(url_for('home_page'))

    api = Api(app)

    class Files(Resource):
        def get(self, page):
            pglen = 10
            record_query = File.query \
                .filter(File.updated_at <= lessthenNow()) \
                .paginate(int(page), pglen, False)

            files = record_query.items
            contents = []
            total = {'files': len(files), 'pglen': pglen}
            for file in files:
                filepath = app.photos.url(file.image)
                info = {}
                info['name'] = file.image
                info['width'] = file.width
                info['height'] = file.height
                info['pcsd'] = file.processed
                info['url'] = filepath
                info['type'] = 'file'

                contents.append(info)
            return {'contents': contents, 'total': total}

    class ObjectClasses(Resource):
        def get(self):
            contents = []

            items = ObjectClass.query.all()
            for tag in items:
                info = {}
                info['value'] = tag.name
                info['color'] = "rgb(" + str(tag.r) + ", " + str(tag.g) + ", " + str(tag.b) + ")"
                contents.append(info)

            return {'tags': contents}

    class ImageDescriptor(Resource):

        def __init__(self, session, **kwargs):
            super(Resource, self).__init__(**kwargs)
            self.session = session
            self.parser = reqparse.RequestParser()
            self.parser.add_argument('description')

        def get(self, name):
            try:
                file = self.session.query(File) \
                    .filter(File.image == name).one()
                return json.dumps({'status': 'ok', 'url': app.photos.url(file.image), 'description': file.description})
            except MultipleResultsFound:
                return json.dumps({'status': 'error', 'error': 'multiple files'})
            except NoResultFound:
                return json.dumps({'status': 'error', 'error': 'no such file'})

        def post(self, name):
            try:
                file = self.session.query(File) \
                    .filter(File.image == name).one()

                args = self.parser.parse_args()
                descr = args['description']
                if not descr:
                    return

                file.description = descr
                file.processed = True
                self.session.commit()

                return json.dumps({'status': 'ok'})
            except MultipleResultsFound:
                return json.dumps({'status': 'error', 'error': 'multiple files'})
            except NoResultFound:
                return json.dumps({'status': 'error', 'error': 'no such file'})

    api.add_resource(Files, '/api/v1/FilesREST/<page>')
    api.add_resource(ImageDescriptor, '/api/v1/ImageREST/<name>', resource_class_kwargs={'session': db.session})
    api.add_resource(ObjectClasses, '/api/v1/ObjectClassesREST')

    return app
예제 #9
0
def create_app():
    app = Flask(__name__)
    dropzone = Dropzone(app)

    app.config['SECRET_KEY'] = 'supersecretkeygoeshere'

    # Dropzone settings
    app.config['DROPZONE_UPLOAD_MULTIPLE'] = True
    app.config['DROPZONE_ALLOWED_FILE_CUSTOM'] = True
    app.config['DROPZONE_ALLOWED_FILE_TYPE'] = 'image/*'
    app.config['DROPZONE_REDIRECT_VIEW'] = 'results'

    # Uploads settingsv
    app.config['UPLOADED_PHOTOS_DEST'] = 'C:/lungapp/abiapp/static/uploads'

    photos = UploadSet('photos', IMAGES)
    configure_uploads(app, photos)
    patch_request_class(app)  # set maximum file size, default is 16MB
    app.config['SECRET_KEY'] = '9OLWxND4o83j4K4iuopO'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'

    db.init_app(app)

    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    @app.route('/upload', methods=['GET', 'POST'])
    def upload():
        # set session for image results
        #app.config['UPLOADED_PHOTOS_DEST'] = 'C:/Users/Abishai/OneDrive/Desktop/abiapp/static/uploads/test'
        if "file_urls" not in session:
            session['file_urls'] = []
        # list to hold our uploaded image urls
        file_urls = session['file_urls']

        # handle image upload from Dropszone
        if request.method == 'POST':
            file_obj = request.files
            for f in file_obj:
                file = request.files.get(f)

                # save the file with to our photos folder
                filename = photos.save(file, name=file.filename)

                # append image urls
                file_urls.append(photos.url(filename))

            session['file_urls'] = file_urls
            return "uploading..."
        # return dropzone template on GET request
        return render_template('upload.html')

    @app.route('/results')
    def results():

        # redirect to home if no images to display
        if "file_urls" not in session or session['file_urls'] == []:
            return redirect(url_for('upload'))

        # set the file_urls and remove the session variable
        file_urls = session['file_urls']
        session.pop('file_urls', None)

        return render_template('results.html', file_urls=file_urls)

    import os

    import io
    import json
    import torch
    import torch.nn.functional as F
    from PIL import Image
    from torch import nn
    from torchvision import transforms as T
    from torchvision import models

    @app.route('/detect', methods=['GET', 'POST'])
    def detect():
        files_list = os.listdir(app.config['UPLOADED_PHOTOS_DEST'])
        return render_template('detect.html', files_list=files_list)

    @app.route('/detectres/<imgg>', methods=['GET', 'POST'])
    def detectres(imgg):
        idx2label = ('Atelectasis', 'Cardiomegaly', 'Consolidation', 'Edema',
                     'Effusion', 'Emphysema', 'Fibrosis', 'Hernia',
                     'Infiltration', 'Mass', 'Nodule', 'Normal Study',
                     'Pleural_thickening', 'Pneumonia', 'Pneumothorax')
        PATH = 'C:\\lungapp\\lungdiseasemodel.pt'

        num_classes = 15
        resnet = models.resnet18(pretrained=False)
        resnet.conv1 = nn.Conv2d(1,
                                 64,
                                 kernel_size=(7, 7),
                                 stride=(2, 2),
                                 padding=(3, 3))
        resnet.fc = nn.Linear(in_features=512,
                              out_features=num_classes,
                              bias=True)
        resnet.load_state_dict(torch.load(PATH))
        resnet.eval()
        file_url = 'C:\\lungapp\\abiapp\\static\\uploads\\' + imgg
        image = open(file_url, 'rb').read()
        target_size = (224, 224)
        image = Image.open(io.BytesIO(image))
        image = T.Resize(target_size)(image)
        image = T.ToTensor()(image)

        # Convert to Torch.Tensor and normalize.
        image = T.Normalize([0.449], [0.226])(image)

        # Add batch_size axis.
        image = image[None]
        ####if use_gpu:
        ####image = image.cuda()
        image = torch.autograd.Variable(image, volatile=True)
        data = {"success": False}
        outputs = resnet(image)
        _, pred = torch.max(outputs.data, 1)

        data['predictions'] = list()
        r = ''.join('%5s' % idx2label[pred])
        data = r

        ress = data
        ress = ''.join(str(e) for e in ress)
        print(ress)
        return render_template("detectres.html", ress=ress)

    from .models import User

    @login_manager.user_loader
    def load_user(user_id):
        # since the user_id is just the primary key of our user table, use it in the query for the user
        return User.query.get(int(user_id))

    # blueprint for auth routes in our app
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    # blueprint for non-auth parts of app
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app
예제 #10
0
파일: app.py 프로젝트: getsec/TorFront
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' # set secret key
app.config.update(
    UPLOADED_PATH=os.path.join(basedir, 'uploads'),
    # Flask-Dropzone config:
    DROPZONE_ALLOWED_FILE_CUSTOM = True, # Allows for custom file types (ie; torrent files)
    DROPZONE_MAX_FILE_SIZE = 1, # 1mb file size
    DROPZONE_FILE_TOO_BIG="That file is too large. 1mb max...", # bad boy
    DROPZONE_ALLOWED_FILE_TYPE = 'image/*, .pdf, .txt, .torrent',
    DROPZONE_MAX_FILES=30 # num of max files
)



dropzone = Dropzone(app) # init upload field



@app.route('/p')
def x():
    
    print(request.cookies)

    return "not good"
    

@app.route('/', methods=['POST', 'GET'])
def home():
    # If post, that means someone added files, put them in the correct dir...
    if request.method == 'POST':
예제 #11
0
"""Flask application entrypoint"""
from __future__ import absolute_import, division, print_function

import flask_monitoringdashboard as dashboard
from flask import Flask
from flask_compress import Compress
from flask_cors import CORS
from flask_dropzone import Dropzone

from deepcell_label import config
from deepcell_label.blueprints import bp
from deepcell_label.models import db

compress = Compress()  # pylint: disable=C0103
dropzone = Dropzone()  # pylint: disable=C0103


class ReverseProxied(object):
    """Enable TLS for internal requests.

    Found in: https://stackoverflow.com/questions/30743696
    """
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        scheme = environ.get('HTTP_X_FORWARDED_PROTO')
        if scheme:
            environ['wsgi.url_scheme'] = scheme
        return self.app(environ, start_response)
예제 #12
0
import time
import os
import ntpath
import base64
import cv2
from flask import render_template, redirect, url_for, request, session, make_response
from flask_dropzone import Dropzone
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
from app import app
from app.smoothing import averaging_yourchoice, gaussian_yourchoice
from app.sharp_image import pos_zero, pos_nonzero, neg_zero, neg_nonzero
# from app.first_order_filter import prewitt_filter, sobel_filter
from app.first_order_filter import prewitt_filter, sobel_filter
from app.unsharp_mask import unsharp_mask  #**

DROPZONE = Dropzone(app)
# Uploads settings
app.config['UPLOADED_PHOTOS_DEST'] = os.getcwd() + '/uploads'
PHOTOS = UploadSet('photos', IMAGES)
configure_uploads(app, PHOTOS)
patch_request_class(app)  # set maximum file size, default is 16MB

FILTER_DISPATCHER = {
    'avg_smoothing': averaging_yourchoice,
    'guass_smoothing': gaussian_yourchoice,
    'laplacian_pos_zero': pos_zero,
    'laplacian_pos_nonzero': pos_nonzero,
    'laplacian_neg_zero': neg_zero,
    'laplacian_neg_nonzero': neg_nonzero,
    'first_order_prewitt': prewitt_filter,
    'first_order_sobel': sobel_filter,
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 14 10:58:10 2019

@author: krunal3kapadiya
PYLINT SCORE: 10/10
"""
from flask import Flask, render_template
from flask_dropzone import Dropzone

APP = Flask(__name__)
DROPZONE = Dropzone(APP)


@APP.route("/")
def index():
    '''
    running index.html file.
    '''
    return render_template('index.html')


if __name__ == '__main__':
    APP.run(port=9000, debug=True)
예제 #14
0
from flask_avatars import Avatars
from flask_bootstrap import Bootstrap
from flask_dropzone import Dropzone
from flask_login import LoginManager, AnonymousUserMixin
from flask_mail import Mail
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_whooshee import Whooshee
from flask_wtf import CSRFProtect

bootstrap = Bootstrap()
db = SQLAlchemy()
login_manager = LoginManager()
mail = Mail()
dropzone = Dropzone()
moment = Moment()
whooshee = Whooshee()
avatars = Avatars()
csrf = CSRFProtect()

@login_manager.user_loader
def load_user(user_id):
	from albumy.models import User
	user = User.query.get(int(user_id))
	return user

login_manager.login_view = 'auth.login'
login_manager.login_message_category = 'warning'
login_manager.refresh_view = 'auth.re_authenticate'
login_manager.needs_refresh_message_category = 'warning'
예제 #15
0
def CreateWallApp():
    app = WallApp(static_folder='assets', static_url_path='/assets')
    app.config.from_object(__name__ + '.ConfigClass')

    try:
        app.config.from_object('local_settings')
    except:
        pass

    # Use for Frontend debug
    CORS(app, resources={r"/api/*": {"origins": "*"}})

    Compress(app)
    Cache(app)
    babel = Babel(app)
    login = LoginManager(app)

    @login.unauthorized_handler
    def handle_needs_login():
        flash("You have to be logged in to access this page.")
        return redirect(url_for('login', next=request.endpoint))

    @app.route("/login", methods=["GET", "POST"])
    def login():
        if request.method == 'POST':
            username = request.form['username']
            password = request.form['password']

            user = User.query.filter(
                or_(User.username == username,
                    User.email == username)).first()
            if user is None or not user.check_password(password):
                flash("Sorry, but you could not log in.")
                redirect(url_for('home_page'))
            else:
                next = request.form['next']
                login_user(user, remember=True)
                return redirect(next)
        else:
            next = request.args.get('next')
            return render_template("login.html", next=next)

    login.login_view = 'login'

    @babel.localeselector
    def get_locale():
        return 'ru'

    app.dropzone = Dropzone(app)
    app.photos = UploadSet('photos', IMAGES)
    configure_uploads(app, app.photos)
    patch_request_class(app)

    @app.route('/')
    def home_page():
        users = db.session.query(func.count(User.id)).scalar()
        images = db.session.query(func.count(Image.id)).scalar()
        is_logedin = current_user.is_authenticated
        return render_template("index.html",
                               files=str(images),
                               users=str(users),
                               is_logedin=is_logedin)

    @app.route('/images_page')
    @login_required
    def images_page():
        return render_template('images_page.html')

    @app.route("/logout")
    @login_required
    def logout():
        logout_user()
        return redirect(url_for('home_page'))

    api = Api(app)

    class Images(Resource):
        def get(self, page):
            pglen = 10
            record_query = Image.query \
                .filter(Image.updated_at <= datetime.now()) \
                .paginate(int(page), pglen, False)

            files = record_query.items
            contents = []
            total = {'files': len(files), 'pglen': pglen}
            for file in files:
                filepath = app.photos.url(file.image)
                info = {}
                info['name'] = file.image
                info['width'] = file.width
                info['height'] = file.height
                info['url'] = filepath
                info['type'] = 'file'

                contents.append(info)
            return {'contents': contents, 'total': total}

    api.add_resource(Images, '/api/v1/FilesREST/<page>')

    return app
예제 #16
0
def _init_plugins(app):
    CKEditor(app)
    Dropzone(app)
    Session(app)
예제 #17
0
from flask_avatars import Avatars
from flask_bootstrap import Bootstrap
from flask_dropzone import Dropzone
from flask_login import LoginManager, AnonymousUserMixin
from flask_mail import Mail
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from flask_whooshee import Whooshee

bootstrap = Bootstrap()
db = SQLAlchemy()
login_manager = LoginManager()
mail = Mail()
dropzone = Dropzone()  # 图片上传
moment = Moment()
whooshee = Whooshee()  # 全文搜索
avatars = Avatars()  # 头像功能
csrf = CSRFProtect()  # 安全模块


@login_manager.user_loader
def loader_user(user_id):
    from photosocial.models import User
    user = User.query.get(int(user_id))
    return user


login_manager.login_view = 'auth.login'
login_manager.login_message_category = 'warning'
login_manager.refresh_view = 'auth.re_authenticate'
예제 #18
0
from flask_dropzone import Dropzone
from flask_login import LoginManager, AnonymousUserMixin
from flask_mail import Mail
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_whooshee import Whooshee
from flask_wtf import CSRFProtect
from flask_ckeditor import CKEditor
from flask_debugtoolbar import DebugToolbarExtension
from flask_caching import Cache

bootstrap = Bootstrap()
db = SQLAlchemy()
login_manager = LoginManager()
mail = Mail()
dropzone = Dropzone()  # 在扩展模块中实例化扩展类
moment = Moment()
whooshee = Whooshee()
avatars = Avatars()
csrf = CSRFProtect()
ckeditor = CKEditor()
toolbar = DebugToolbarExtension()
cache = Cache()


@login_manager.user_loader
def load_user(user_id):
    from albumy.models import User
    user = User.query.get(int(user_id))
    return user
예제 #19
0
from collections import defaultdict
from flask_dropzone import Dropzone

from werkzeug.middleware.proxy_fix import ProxyFix
from flask import Flask, request, send_file, render_template, abort, jsonify, redirect, url_for
from flask_cors import CORS
from flask_basicauth import BasicAuth
from flasgger import Swagger

import utils
import worker
import database

application = Flask(__name__)
dropzone = Dropzone(application)

# application.config['DROPZONE_UPLOAD_MULTIPLE'] = True
# application.config['DROPZONE_PARALLEL_UPLOADS'] = 3

DEVELOPMENT = os.environ.get('environment',
                             'production').lower() == 'development'

if not DEVELOPMENT:
    # In some setups this proved to be necessary for url_for() to pick up HTTPS
    application.wsgi_app = ProxyFix(application.wsgi_app, x_proto=1)

CORS(application)
application.config['SWAGGER'] = {
    'title':
    os.environ.get('APP_NAME', 'ifc-pipeline request API'),
예제 #20
0
    {
        "field": "attention",
        "title": "attention",
        "sortable": True,
    },
    {
        "field": "uneven",
        "title": "uneven",
        "sortable": True,
    }
]


app = Flask(__name__)
Bootstrap(app)
Dropzone(app)
nav=Nav()
nav.register_element('top',Navbar(u'ISPM Accelerator',
                                    View(u'Home','index'),
                                    Subgroup(u'Service',
                                             View(u'RRIC Shareholding Rule Recon','shareholding_rule_recon'),

                                             Separator(),
                                             View(u'FCMO Monthly Report Automation', 'index'),
                                    ),
))

nav.init_app(app)


@app.route('/shareholding_rule_recon_uploads', methods=['GET', 'POST'])
예제 #21
0
img = Blueprint('img', __name__)
basedir = os.path.abspath(os.path.dirname(__file__)) #ディレクトリ名を取得

app = Flask(__name__)

with app.app_context():
    current_app.config.update(
        UPLOADED_PATH=os.path.join(basedir, ''), #絶対パス
        # Flask-Dropzone config:
        DROPZONE_ALLOWED_FILE_TYPE='image',
        DROPZONE_MAX_FILE_SIZE=3,
        DROPZONE_MAX_FILES=30,
    )

    dropzone = Dropzone(current_app)



"""
    FunctionName    :   upload
    Data            :   2020/07/21
    Designer        :   野田啓介
    Function        :   レシート画像をアップロードする
    Entry           :   userID   --- ユーザーID
    Return          :   SearchOrderThingメソッドにリダイレクトする
                        userID   --- ユーザーID
                        fileName --- レシート画像のファイル名
"""
@img.route('/upload/<userID>', methods=['GET', 'POST'])
def upload(userID):
예제 #22
0
def create_app(config_filename=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    basedir = os.path.abspath(os.path.dirname(__file__))

    app.config.update(
        UPLOADED_PATH=os.path.join(basedir, 'static'),
        # Flask-Dropzone config:
        DROPZONE_ALLOWED_FILE_TYPE='image',
        DROPZONE_MAX_FILE_SIZE=2,
        DROPZONE_MAX_FILES=2,
        DROPZONE_UPLOAD_ON_CLICK=True,
    )

    dropzone = Dropzone(app)
    result = {}
    app.config["DEBUG"] = True
    if config_filename:
        app.config.from_pyfile(config_filename)

    def similarity(f1_name, f2_name):
        try:

            f1 = os.path.join(app.config['UPLOADED_PATH'], f1_name)
            f2 = os.path.join(app.config['UPLOADED_PATH'], f2_name)
            id = f1_name[:8] + f2_name[:8] + ".png"
            pixel_match_file = os.path.join(app.config['UPLOADED_PATH'],
                                            "PM_" + id)
            feature_match_file = os.path.join(app.config['UPLOADED_PATH'],
                                              "FM_" + id)
            feature_diff_file1 = os.path.join(app.config['UPLOADED_PATH'],
                                              "FD1_" + id)
            feature_diff_file2 = os.path.join(app.config['UPLOADED_PATH'],
                                              "FD2_" + id)
            catagory_match_file = os.path.join(app.config['UPLOADED_PATH'],
                                               "CM_" + id)
            app.logger.debug('comparing %s with %s', f1, f2)
            pd = simple_pixel_diff(f1, f2, pixel_match_file)
            app.logger.debug('pixel matching score: %f', pd)
            feature_match_score = feature_matching(f1, f2, feature_match_file)
            app.logger.debug('feature matching score: %d', feature_match_score)

            feature_diff_score = feature_diff(f1, f2, feature_diff_file1,
                                              feature_diff_file2)

            category1 = img_classification(f1)
            category2 = img_classification(f2)

            euclidean_distance, cosine_distance = img_similarity(f1, f2)

            return {
                'f1': f1_name,
                'f2': f2_name,
                'success': True,
                'pixel_match_score': pd,
                'pixel_match_img': "PM_" + id,
                'feature_match_score': feature_match_score,
                'feature_match_img': "FM_" + id,
                'euclidean_distance': euclidean_distance,
                'cosine_distance': cosine_distance,
                'category_match_img': "CM_" + id,
                'feature_diff_score': feature_diff_score,
                'feature_diff_img1': "FD1_" + id,
                'feature_diff_img2': "FD2_" + id,
                "category1": category1,
                "category2": category2
            }
        except:
            traceback.print_exc()
            return {'success': False, 'utterances': None}

    @app.route('/', methods=['GET'])
    def home():
        return render_template('index.html')

    @app.route('/upload', methods=['POST'])
    def upload():
        files = []
        if request.method == 'POST':
            for key, f in request.files.items():
                if key.startswith('file'):
                    name = random_filename(f.filename)
                    f.save(os.path.join(app.config['UPLOADED_PATH'], name))
                    files.append(name)
                    app.logger.info('saving %s', f.filename)
        app.logger.debug('received %d', len(files))

        return jsonify({"files": files})

    @app.route('/diff', methods=['GET'])
    def completed():
        f1 = request.args.get('f1')
        f2 = request.args.get('f2')
        res = similarity(f1, f2)

        return render_template('response.html', res=res)

    return app
예제 #23
0
import cv2
import numpy as np
from keras.preprocessing import image
from keras.models import model_from_json
# Imports PIL module  
from PIL import Image 
import tensorflow as tf
import pickle
#####################################################
from flask_cors import CORS, cross_origin
import requests
from bs4 import BeautifulSoup
from newspaper import Article
#####################################################
app = Flask(__name__)
dropzone = Dropzone(app)    # INIT DROPZONE FOR FILE UPLOAD
#run_with_ngrok(app)  
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

""" LOADING DEVNET -- """
cmfdModel = create_CMFD_model('./pretrained_devNet.hd5')
print("------- DevNet Loaded from Disk --------")
# load model from JSON file
with open("modela.json", "r") as json_file:
    loaded_model_json = json_file.read()
    loaded_model = model_from_json(loaded_model_json)

# load weights into the new model
loaded_model.load_weights("modelNNa.h5")
print("-------- Model loaded from disk --------")
예제 #24
0
# Flask config
# set request body's max length
# app.config['MAX_CONTENT_LENGTH'] = 3 * 1024 * 1024  # 3Mb

# Flask-CKEditor config
app.config['CKEDITOR_SERVE_LOCAL'] = True
app.config['CKEDITOR_FILE_UPLOADER'] = 'upload_for_ckeditor'

# Flask-Dropzone config
app.config['DROPZONE_ALLOWED_FILE_TYPE'] = 'image'
app.config['DROPZONE_MAX_FILE_SIZE'] = 3
app.config['DROPZONE_MAX_FILES'] = 30

ckeditor = CKEditor(app)
dropzone = Dropzone(app)


@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template('index.html')


@app.route('/html', methods=['GET', 'POST'])
def html():
    form = LoginForm()
    print(form.username())
    if request.method == 'POST':
        username = request.form.get('username')
        flash('Welcome home, %s!' % username)
        return redirect(url_for('index'))
예제 #25
0
def create_app():

    app = Flask(__name__)
    app.config.from_object(__name__)

    # Check Configuration section for more details
    # And here: http://codeomitted.com/flask-session-aws-redis/
    # From here: https://pythonhosted.org/Flask-Session/
    app.config['SESSION_TYPE'] = 'redis'
    # Note: to work locally, 'redis' should be pointing to 127.0.0.1 in the hosts file
    app.config['SESSION_REDIS'] = redis.Redis(host='redis', port=6379)
    Session(app)

    app.config.update(
        # UPLOADED_PATH=os.path.join(BASEDIR, 'uploads'), # possibly unnecessary
        # Flask-Dropzone config:
        DROPZONE_ALLOWED_FILE_TYPE='image',
        DROPZONE_MAX_FILE_SIZE=5,
        DROPZONE_MAX_FILES=100,
        DROPZONE_UPLOAD_ON_CLICK=True,
        DROPZONE_REDIRECT_VIEW='collage',
    )

    dropzone = Dropzone(app)

    @app.route('/', methods=['POST', 'GET'])
    def index():
        """
        1. check if user exists, if not, add it to session object
        2. create a temporary folder to store uploaded images
        3. save all uploaded images
        4. if new user, make folder for collages, if old user, folder already exists
        5. make collage
        6. save collage to user folder

        :return: rendered home page template
        """

        # handle users regardless of the method
        user_id = handle_user()

        if request.method == 'GET':
            pass
        elif request.method == 'POST':
            # TODO: handle cases with different images with the same name
            # f is werkzeug.datastructures.FileStorage
            with tempfile.TemporaryDirectory() as tempdir:
                for key, f in request.files.items():
                    if key.startswith('file'):
                        f.save(os.path.join(tempdir, f.filename))
                        print('RECEIVED AND SAVED AN IMAGE!')
                print("ALL IMAGES UPLOADED.")
                make_collage(user_id, tempdir)
                print("COLLAGE MADE!")
        return render_template('index.html',
                               max_images=app.config['DROPZONE_MAX_FILES'],
                               max_file_size=app.config['DROPZONE_MAX_FILE_SIZE'])

    @app.route('/collage')
    def collage():
        """
        Present all existing user's collages.

        Loop through existing files in user's directory and keep only .png
        Pass their paths to `collages.html` template.

        :return: rendered collages template
        """
        if 'user' in session:
            user_path = USERS_DIR/session['user']

            # only keep `.png` files
            sorted_file_paths = sort_from_new_to_old([str(f) for f in user_path.iterdir() if str(f).endswith('.png')])

            # only keep path after 'static/`; it will be used with url_for('static')
            collages_paths = [str(f).split('static/')[1] for f in sorted_file_paths]

            return render_template('collages.html', collages=collages_paths)
        else:
            return "<h1>You don't have any collages yet.</h1>"

    @app.route('/user')
    def user():
        """
        Inform the user of their unique user id.

        :return: information about the user id
        """

        if 'user' in session:
            return f"<h1>Your user id is: {session['user']}</h1>"
        else:
            return "This is a new user."

    return app