html 在网页上的警报通知中,未通过 AJAX 返回FLASK调用的结果

vptzau2j  于 2023-02-17  发布在  其他
关注(0)|答案(1)|浏览(91)

基本上我比较两个文本一个输入是pdf,另一个基本文本。我已经创建了索引html和内是另一个html为位清晰度。使用python FLASK功能。所有的代码单独运行,所有提到的错误无效输入一起运行非常好,它只是主要的结果输出,我想我在调用和执行main函数时可能有点混乱,因为所有的警报和文件检查都在工作,flask内部的逻辑也在工作。
我的html文件与 AJAX 和形式:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    
    function submitForm() {
      // Show the loading screen
      document.getElementById("loading").style.display = "block";

      // Get the input values
      var JD = document.getElementById("JD").value;
      var file = document.getElementById("FL").file[0];

      // Check if a file has been selected and is a pdf
      if (!file || file.type !== 'application/pdf') {
        alert("Please select a valid PDF file");
        return;
      }

      // Check if file size is less than 5 MB
      if (file.size > 5000000) {
        alert("File size should not exceed 5 MB");
        return;
      }

      // Create a FormData object to send both the file and the jd to the API
      var formData = new FormData($('#upload_form')[0]);
      formData.append("FL", FL);
      formData.append("JD", JD);

      // Make the API call
      $.ajax({
        url: base_url + "api/Analyze",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function(result) {
          // Hide the loading screen
          document.getElementById("loading").style.display = "none";
          alert(result);
        },
        error: function () {
          // Hide the loading screen
          document.getElementById("loading").style.display = "none";

          // Display the error
          alert("Error during API call");
        }
      });
    }
  </script>
</head>
<body>
  <h2>Analysis</h2>
  <form id="upload_form" enctype="multipart/form-data">
    <p>
      <label for="JD">Description:</label>
      <textarea name = "JD" id="JD" rows="4" cols="50"></textarea>
    </p>
    <p>
      <label for="FL">FILE:</label>
      <input type="file" name="FL" id="FL" accept="application/pdf">
    </p>
    <p>
      <input type="button" value="Submit" onclick="submitForm()">
    </p>
  </form>
  <div id="loading" style="display: none;">Loading...</div>

这是www.example.com的app.py flask 文件-

from flask import Flask, render_template, redirect, request, jsonify
import fitz
import re
import sys
#(please ignore irrelevant imports)

app = Flask(__name__)

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

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

#(ignore this bulk one)
@app.route('/BulkAnalyze', methods=['GET'])
def bulk_analyze():
    return render_template('Bulk.html')

@app.route('/api/Analyze', methods=['POST'])
def Submit():
    pdf_file = request.files['FL']
    jd_text = request.form['JD']
    
    jd_text = " ".join(jd_text.split('\n'))

    with fitz.open(pdf_file) as doc:
        text = ''
        for page in doc:
            text += page.get_text()
    text = ' '.join(text.split('\n'))

# Perform text comparison
    matching_words = [word for word in jd_text.split() if word in text.split()]
    match = 100 * len(matching_words) / len(jd_text.split())
    return jsonify({'result': 'The matching percentage is :' + match })

if __name__ == "__main__":
    app.run()

我试图比较这两个文本输入,以获得百分比输出作为警报。我知道我可以在页面或其他网页上显示输出来规避这个问题,但这不是一些irl问题,我很想从中学习。

5fjcxozz

5fjcxozz1#

上载的文件会在服务器端生成一个FileStorage类型的对象。对于加载的PDF文件,它是一个类似文件的对象。无法直接从FileStorage对象提取文本。必须首先将数据读入流中。
下面是根据您的代码稍微修改的示例。

from flask import (
    Flask, 
    jsonify, 
    redirect, 
    render_template, 
    request
)
import fitz
import io
import re

app = Flask(__name__)

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

@app.post('/api/analyze')
def api_analyze():
    pcnt = 0
    try:
        desc = request.form['desc']
        file = request.files['file']

        with io.BytesIO(file.read()) as fh, fitz.open(stream=fh, filetype='pdf') as doc:
            text = ' '.join(page.get_text() for page in doc)
        
        tokens_desc = set(re.findall(r'\b\w+\b', desc))
        tokens_text = set(re.findall(r'\b\w+\b', text))
        tokens_match = tokens_text & tokens_desc

        pcnt = len(tokens_match) / len(tokens_desc) * 100
    finally:
        return jsonify(result=f'The matching percentage is: {pcnt}%')
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Index</title>
</head>
<body>

    <form name="upload-form">
        <div>
            <label for="file">Choose a file:</label>
            <input type="file" name="file" id="file" accept="application/pdf" />
        </div>
        <div>
            <label for="desc">Description:</label>
            <textarea name="desc" id="desc" rows="4" cols="50"></textarea>
        </div>
        <div>
            <input type="submit" value="Submit" />
        </div>
    </form>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(function() {
            $('form[name="upload-form"]').submit(function(event) {
                event.preventDefault();

                const file = this['file'].files[0];
                if (!file || file.type !== 'application/pdf') {
                    alert('Please select a valid PDF file');
                    return;
                }

                if (file.size > 5000000) {
                    alert('File size should not exceed 5 MB');
                    return;
                }

                $.ajax({
                    url: '/api/analyze', 
                    type: 'post', 
                    data: new FormData(this), 
                    processData: false, 
                    contentType: false
                }).done(function(data) {
                    alert(data.result);
                }).fail(function() {
                    alert('Error during API call.');
                });
            })
        });
    </script>
    
</body>
</html>

相关问题