英文:
No return of result from FLASK call via AJAX in an alert notifcation on the web page
问题
以下是你要翻译的内容:
基本上,我正在比较两个文本,一个输入是PDF,另一个是基本文本。我已经创建了一个包含另一个HTML的索引HTML,以提高清晰度,使用了Python的FLASK功能。所有代码都是分开运行的,所有提到的有关无效输入的错误都很好地一起运行,只是主要结果输出,我认为我在调用和执行主函数时出了问题,因为所有警报和文件检查都在工作,Flask内部的逻辑也在工作。
我的带有Ajax和表单的HTML文件:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function submitForm() {
// 显示加载屏幕
document.getElementById("loading").style.display = "block";
// 获取输入值
var JD = document.getElementById("JD").value;
var file = document.getElementById("FL").file[0];
// 检查是否已选择文件且为PDF
if (!file || file.type !== 'application/pdf') {
alert("请选择有效的PDF文件");
return;
}
// 检查文件大小是否小于5 MB
if (file.size > 5000000) {
alert("文件大小不应超过5 MB");
return;
}
// 创建一个FormData对象,以发送文件和jd到API
var formData = new FormData($('#upload_form')[0]);
formData.append("FL", FL);
formData.append("JD", JD);
// 进行API调用
$.ajax({
url: base_url + "api/Analyze",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(result) {
// 隐藏加载屏幕
document.getElementById("loading").style.display = "none";
alert(result);
},
error: function () {
// 隐藏加载屏幕
document.getElementById("loading").style.display = "none";
// 显示错误
alert("API调用期间出现错误");
}
});
}
</script>
</head>
<body>
<h2>分析</h2>
<form id="upload_form" enctype="multipart/form-data">
<p>
<label for="JD">描述:</label>
<textarea name="JD" id="JD" rows="4" cols="50"></textarea>
</p>
<p>
<label for="FL">文件:</label>
<input type="file" name="FL" id="FL" accept="application/pdf">
</p>
<p>
<input type="button" value="提交" onclick="submitForm()">
</p>
</form>
<div id="loading" style="display: none;">加载中...</div>
这是app.py Flask文件:
from flask import Flask, render_template, redirect, request, jsonify
import fitz
import re
import sys
#(请忽略不相关的导入)
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')
#(忽略这个大块的代码)
@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'))
# 执行文本比较
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': '匹配百分比为:' + match })
if __name__ == "__main__":
app.run()
我试图比较这两个文本输入以获得一个百分比输出作为警报。我知道我可以在页面上显示输出来规避这个问题,但这不是一个实际的问题,我想从中学习。
英文:
Basically I a comparing two texts one input is a pdf, another basic text.
I have created index html and within is another html for a bit clarity. using python FLASK feature.
All the code runs separately, all mentioned errors for invalid input run very fine together, its just the main result output, I presume I am messing up somehow in calling and executing the main function because all the alerts and file checks are working , and the logic inside of flask is working too.
My html file with ajax and form :
<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>
And this is the app.py flask file -
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()
I was trying to compare those two text input to get a percentage output as an alert.
I am aware i could display output on page or another webpage to circumnavigate this issue, but this is not some irl problem and i would love to learn from this.
答案1
得分: 0
以下是您要翻译的内容:
"An uploaded file results in an object of type FileStorage on the server side. It is a file-like object for the loaded PDF file. It is not possible to extract the text directly from the FileStorage object. The data must first be read into a stream."
以下是基于您的代码稍作修改后的示例。
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">选择文件:</label>
<input type="file" name="file" id="file" accept="application/pdf" />
</div>
<div>
<label for="desc">描述:</label>
<textarea name="desc" id="desc" rows="4" cols="50"></textarea>
</div>
<div>
<input type="submit" value="提交" />
</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('请选择有效的PDF文件');
return;
}
if (file.size > 5000000) {
alert('文件大小不应超过5MB');
return;
}
$.ajax({
url: '/api/analyze',
type: 'post',
data: new FormData(this),
processData: false,
contentType: false
}).done(function(data) {
alert(data.result);
}).fail(function() {
alert('API调用期间出现错误。');
});
})
});
</script>
</body>
</html>
英文:
An uploaded file results in an object of type FileStorage on the server side. It is a file-like object for the loaded PDF file. It is not possible to extract the text directly from the FileStorage object. The data must first be read into a stream.
The following is the slightly modified example based on your code.
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论