Esempio n. 1
0
 def addCorpusUser(self, corpus_name, email, is_owner=False):
     corpus = Corpus.query.filter(Corpus.name == corpus_name).first()
     user = User.query.filter(User.email == email).first()
     new_cu = CorpusUser(corpus=corpus, user=user, is_owner=is_owner)
     self.db.session.add(new_cu)
     self.db.session.commit()
     return new_cu
Esempio n. 2
0
def manage_corpus_users(corpus_id):
    """
         Save or display corpus accesses
     """
    corpus = Corpus.query.filter(Corpus.id == corpus_id).first()

    can_read = corpus.has_access(current_user)
    can_edit = current_user.is_admin() or corpus.is_owned_by(current_user)

    if can_read is True:
        # only owners can give/remove access & promote a user to owner
        if request.method == "POST" and can_edit:
            users = [
                User.query.filter(User.id == user_id).first()
                for user_id in [int(u) for u in request.form.getlist("user_id")]
            ]
            ownerships = [int(u) for u in request.form.getlist("ownership") if u.isdigit()]

            # previous rights
            prev_cu = CorpusUser.query.filter(CorpusUser.corpus_id == corpus_id).all()
            prev_clu = ControlListsUser.query.filter(
                ControlListsUser.control_lists_id == corpus.control_lists_id).all()

            # should not be able to delete the last owner
            if len(prev_cu) > 0 and True not in set([user.id in ownerships for user in users]):
                abort(403)

            # update corpus users
            try:
                for cu in prev_cu:
                    db.session.delete(cu)
                for cu in [CorpusUser(corpus=corpus, user=user, is_owner=user.id in ownerships)
                           for user in users]:
                    db.session.add(cu)
                update_control_list_user(corpus, prev_clu, users, _commit=False)
                db.session.commit()
                flash('Modifications have been saved.', 'success')
            except Exception as e:
                db.session.rollback()
            return redirect(url_for('main.dashboard'))

        else:
            # GET method
            users = User.query.all()
            roles = Role.query.all()
            return render_template_with_nav_info(
                'main/dashboard_manage_corpus_users.html',
                corpus=corpus, current_user=current_user, users=users, roles=roles,
                can_read=can_read, can_edit=can_edit
            )
    else:
        return abort(403)
Esempio n. 3
0
    def add_n_corpora(self, n_corpus: int, **kwargs):
        if not self.AUTO_LOG_IN:
            raise Exception("This function only works with autologin")

        user = User.query.filter(
            User.email == self.app.config['ADMIN_EMAIL']).first()
        for n in range(n_corpus):
            corpus = Corpus(name="a" * n,
                            control_lists_id=1,
                            columns=[
                                Column(heading="Lemma"),
                                Column(heading="POS"),
                                Column(heading="Morph"),
                                Column(heading="Similar"),
                            ])
            new_cu = CorpusUser(corpus=corpus, user=user, is_owner=True)
            db.session.add(corpus)
            db.session.add(new_cu)
            db.session.flush()
        db.session.commit()
Esempio n. 4
0
def corpus_new():
    """ Register a new corpus
    """
    lemmatizers = current_app.config.get("LEMMATIZERS", [])

    def normal_view():
        return render_template_with_nav_info(
            'main/corpus_new.html',
            lemmatizers=lemmatizers,
            public_control_lists=_get_available(),
            tsv=request.form.get("tsv", "")
        )

    def error():
        return normal_view(), 400

    if request.method == "POST":
        if not current_user.is_authenticated:
            abort(403)
        elif not len(strip_or_none(request.form.get("name", ""))):
            flash("You forgot to give a name to your corpus", category="error")
            return error()
        else:
            form_kwargs = {
                "name": request.form.get("name"),
                "context_left": request.form.get("context_left", None),
                "context_right": request.form.get("context_right", None),
                "delimiter_token": strip_or_none(request.form.get("sep_token", "")) or None,
                "columns": [
                    Column(heading="Lemma"),
                    Column(heading="POS"),
                    Column(heading="Morph"),
                    Column(heading="Similar"),
                ]
            }
            for column in form_kwargs["columns"]:
                column.hidden = bool(
                    request.form.get(f"{column.heading.lower()}Column", "")
                )
            if (
                "lemmaColumn" in request.form
                and "posColumn" in request.form
                and "morphColumn" in request.form
            ):
                flash(
                    "You can't disable Lemma and POS and Morph. Keep at least one of them.",
                    category="error"
                )
                return error()

            if request.form.get("control_list") == "reuse":
                tokens = read_input_tokens(request.form.get("tsv"))
                try:
                    control_list = ControlLists.query.get_or_404(request.form.get("control_list_select"))
                except Exception:
                    flash("This control list does not exist", category="error")
                    return error()
                form_kwargs.update({"word_tokens_dict": tokens,
                                    "control_list": control_list})
                cl_owner = False
            else:
                tokens, allowed_lemma, allowed_morph, allowed_POS = create_input_format_convertion(
                    request.form.get("tsv"),
                    request.form.get("allowed_lemma", None),
                    request.form.get("allowed_morph", None),
                    request.form.get("allowed_POS", None)
                )
                cl_owner = True
                form_kwargs.update({"word_tokens_dict": tokens, "allowed_lemma": allowed_lemma,
                                    "allowed_POS": allowed_POS, "allowed_morph": allowed_morph})

            try:
                corpus = Corpus.create(**form_kwargs)
                db.session.add(CorpusUser(corpus=corpus, user=current_user, is_owner=True))
                # Add a link to the control list
                ControlLists.link(corpus=corpus, user=current_user, is_owner=cl_owner)
                db.session.commit()
                flash("New corpus registered", category="success")
                return redirect(url_for(".corpus_get", corpus_id=corpus.id))
            except (sqlalchemy.exc.StatementError, sqlalchemy.exc.IntegrityError) as e:
                db.session.rollback()
                flash("The corpus cannot be registered. Check your data", category="error")
                if str(e.orig) == "UNIQUE constraint failed: corpus.name":
                    flash("You have already a corpus going by the name {}".format(request.form.get("name")),
                          category="error")
                return error()
            except MissingTokenColumnValue as exc:
                db.session.rollback()
                flash("At least one line of your corpus is missing a token/form. Check line %s " % exc.line, category="error")
                return error()
            except NoTokensInput:
                db.session.rollback()
                flash("You did not input any text.", category="error")
                return error()
            except ValidationError as exception:
                db.session.rollback()
                flash(exception, category="error")
                return error()
            except Exception as e:
                db.session.rollback()
                flash("The corpus cannot be registered. Check your data", category="error")
                return error()

    return normal_view()