def inputform():
    form = QueryForm()
    if form.validate_on_submit():

        query = form.query.data
        df = pd.read_pickle('cmu_data_phrase.pkl')

        #Get top-n entries by score ranking
        df['score'] = df.apply(lambda row: get_score(
            query, row.noun_phrase, row.sentiment, alpha=0.95),
                               axis=1)
        df_topn = df.nlargest(500, 'score')
        df_topn.reset_index(inplace=True)

        recommendations = get_recommendation(query,
                                             df,
                                             df_topn,
                                             n=500,
                                             NUM_CLUSTERS=10)
        # session['btitle'] = []
        # for book in recommendations:
        # 	session['btitle'].append(book['book_title'])

        # flash('Query Submitted!','success')
        return render_template('output.html',
                               recommendations=recommendations,
                               query=query)
    return render_template('inputform.html', form=form)
Exemplo n.º 2
0
def home():
    global q_str, doc_dict, posting, info, q_res
    if not (os.path.exists(rindex_file) and os.path.exists(docs_file)):
        ind_f = open(rindex_file, 'w')
        doc_f = open(docs_file, 'w') 
        createIndex()
        json.dump(doc_dict, doc_f)
        json.dump(posting, ind_f)
        doc_f.close()
        ind_f.close()
    else:
        ind_f = open(rindex_file)
        doc_f = open(docs_file) 
        d_dict = json.load(doc_f)
        doc_dict = { int(key):val for key,val in d_dict.items() }
        posting = json.load(ind_f)
        info = str(len(doc_dict)) + ' documents indexed with '\
                + str(len(posting)) + ' unique words'
        doc_f.close()
        ind_f.close()
        

    content = {'info':info, 'res':q_res}
    form = QueryForm()
    if form.validate_on_submit():
        q_str = form.queryid.data
        return redirect('/query')
    return render_template('home.html', 
                            content = content,
                            form = form)
Exemplo n.º 3
0
def delete_item():
    form = QueryForm()
    if form.validate_on_submit():
        db_session.query(Items).filter_by(name=form.name.data).delete(
            synchronize_session=False)
        db_session.commit()
        return redirect(url_for('success'))
    return render_template('delete.html', form=form)
Exemplo n.º 4
0
def homepage():
    """
    Render the homepage template on the / route
    """
    form = QueryForm()
    if form.validate_on_submit():
        return redirect(url_for('home.show_results'), code=307)

    return render_template('home/index.html', form=form, title="Psiholeks")
Exemplo n.º 5
0
def queryPage():
    results = None
    table = None
    form = QueryForm()

    if form.validate_on_submit():
        table, results = query()

    return render_template('query.html', query=form, queryResult=results, table=table,
                           isAdmin=config.adminLoggedIn)
Exemplo n.º 6
0
def main_page():

    form = QueryForm()
    if form.validate_on_submit():
        movies = between_years(form.min_year.data, form.max_year.data,
                               form.number.data)
        m = [
            json.dumps(movie.__dict__, ensure_ascii=False) for movie in movies
        ]
        session['movies'] = m
        return redirect(url_for('movie_list'))
    return render_template('form.html', form=form)
Exemplo n.º 7
0
def index():
    query_form = QueryForm()
    # 调用WTF的函数实现验证
    if query_form.validate_on_submit():
        # 验证通过 获取数据

        input_word = query_form.word.data
        # 判断单词是否存在 查询数据库
        session = Session()
        word = session.query(Dictionary).filter_by(word=input_word).first()
        if word:
            # try:

            words = session.query(Dictionary).filter_by(word=input_word)
            # print(words)
            session.close()
            return render_template("index.html", form=query_form, words=words)

        else:

            try:
                paraph = youdao.get_data(input_word)
                new_word = Dictionary(word=paraph[0],
                                      IPA=paraph[1],
                                      paraphrase=paraph[2],
                                      example_sentence=paraph[3] + paraph[4],
                                      other=paraph[5])
                session.add(new_word)
                session.commit()

                flash("添加成功")
                words = session.query(Dictionary).filter_by(word=input_word)

                session.close()
                return render_template("index.html",
                                       form=query_form,
                                       words=words)
            except Exception as e:
                print(e)
                flash("添加失败")
                session.rollback()
                words = session.query(Dictionary).order_by(
                    func.rand()).limit(5)
                session.close()
                return render_template("index.html",
                                       form=query_form,
                                       words=words)
    session = Session()
    words = session.query(Dictionary).order_by(func.rand()).limit(5)
    session.close()
    return render_template("index.html", form=query_form, words=words)
Exemplo n.º 8
0
def demo_page():
    form = QueryForm()
    if form.validate_on_submit():
        word = form.word.data
        model = form.model.data
        conf = form.conf.data
        iteration = form.iteration.data
        results, var_count = search_UrbanDict(word, model, conf, iteration)
        return render_template('index.html',
                               data=results,
                               var_count=var_count,
                               form=form)

    return render_template('index.html', form=form)
Exemplo n.º 9
0
def submit_queries():
    qform = QueryForm()
    error = None
    data = ""
    if qform.validate_on_submit():
        #user input
        patient_id = qform.p_id.data
        start_date = qform.start_date.data
        end_date = qform.end_date.data
        query_type = qform.query_type.data
        data = run_query(patient_id, start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d'), query_type)
    else:
        data = "Not Ready"
        return render_template('queries.html', error=error, form=qform, results=data)

    return render_template('queries.html', error=error, form=qform, results=data)
Exemplo n.º 10
0
def query():
    sno = {}
    sname = {}
    class_1 = {}
    class_2 = {}
    class_3 = {}
    class_4 = {}
    class_5 = {}
    qz = {}
    qm = {}
    group = {}
    chaiji = {}
    form = QueryForm()
    if form.validate_on_submit():
        num = form.student_number.data
        results = Marks_record.query.filter_by(username=num).order_by(
            Marks_record.id.asc()).first()
        sno[num] = results.sno
        sname[num] = results.sname
        class_1[num] = results.class_1
        class_2[num] = results.class_2
        class_3[num] = results.class_3
        class_4[num] = results.class_4
        class_5[num] = results.class_5
        qz[num] = results.qz
        qm[num] = results.qm
        group[num] = results.group
        chaiji[num] = results.chaiji
    return render_template('main/query.html',
                           form=form,
                           sno=sno,
                           sname=sname,
                           class_1=class_1,
                           class_2=class_2,
                           class_3=class_3,
                           class_4=class_4,
                           class_5=class_5,
                           qz=qz,
                           qm=qm,
                           group=group,
                           chaiji=chaiji)
Exemplo n.º 11
0
def index():
    form = QueryForm()
    if form.validate_on_submit():
        result_url = "/val={}".format(form.number.data)
        return redirect(result_url)
    return render_template("index.html", form=form)
Exemplo n.º 12
0
def query_item():
    form = QueryForm()
    if form.validate_on_submit():
        results = db_session.query(Items).filter_by(name=form.name.data).all()
        return str(results)
    return render_template('query.html', form=form)
Exemplo n.º 13
0
def runquery():
    form = QueryForm()
    query_results = []
    columns = []
    if form.validate_on_submit():
        try:
            s = str(form.query.data)
            s = s.strip()
            if s.find(';') == -1:
                raise Exception("Semicolon (;) missing")
            if s.find(';') != len(s) - 1:
                raise Exception("Multiple queries not allowed")
            try:
                cursor.execute(form.query.data)
            except:
                re_connect()
                cursor.execute(form.query.data)
            results = cursor.fetchall()
            columns = cursor.column_names
            query_results = results
        except Exception as e:
            if ("Table" in str(e)) and ("doesn't exist" in str(e)):
                # means has to suggest table also...
                if all_table_names == []:
                    fill_all_table_names()
                last_index = str(e).find("' doesn't")
                first_index = str(e).find("'antique_store")
                suggestion = difflib.get_close_matches(
                    str(e)[first_index + 15:last_index], all_table_names)
                #print('Error: ' + str(e) + "\n Do you mean: " + str(suggestion))
                if (suggestion == []):
                    message = 'Error: ' + str(
                        e
                    ) + "... NO table found in the database with similar name "
                else:
                    message = 'Error: ' + str(e) + "... Do you mean: " + str(
                        suggestion)
                flash(message, 'danger')

            elif "Unknown column" in str(e):
                first_index = 16 + str(e).find("Unknown column")
                last_index = str(e).find("' in 'field list'")
                column_name_inserted = str(e)[first_index:last_index]
                q = str(form.query.data)
                table_name = q[q.find("from") + 5:-1]
                column_names = get_column_names(table_name)
                #print(column_names)
                #print(column_name_inserted)
                suggestion = difflib.get_close_matches(column_name_inserted,
                                                       column_names)
                if (suggestion == []):
                    message = 'Error: ' + str(
                        e
                    ) + "...... NO column found in the table with similar name "
                else:
                    message = 'Error: ' + str(
                        e) + "...... Do you mean: " + str(suggestion)
                flash(message, 'danger')

            else:
                flash('Error: ' + str(e), 'danger')
        else:
            flash('Query run successfully!', 'success')
    # if request.method == 'POST':
    #     if request.form['export_btn'] == "export to csv":
    #         si = StringIO.StringIO()
    #         cw = csv.writer(si)
    #         cw.writerow([columns])
    #         cw.writerows(query_results)
    #         response = make_response(si.getvalue())
    #         response.headers['Content-Disposition'] = 'attachment; filename=report.csv'
    #         response.headers["Content-type"] = "text/csv"
    #         return response
    return render_template('runquery.html',
                           form=form,
                           columns=columns,
                           query_results=query_results,
                           title='Run query')