from flask import Flask, request, jsonify import torch from transformers import BertTokenizer, BertForSequenceClassification import logging app = Flask(name) logging.basicConfig(level=logging.INFO) tokenizer = BertTokenizer.from_pretrained('bert-base-chinese') model = BertForSequenceClassification.from_pretrained('bert-base-chinese', num_labels=2) model.eval() @app.route('/classify', methods=['POST']) def classify(): try: text = request.json['text'] inputs = tokenizer(text, return_tensors='pt') outputs = model(**inputs) logits = outputs.logits probabilities = torch.softmax(logits, dim=1) predicted_label = torch.argmax(probabilities, dim=1).item() if predicted_label == 0: result = '负面' else: result = '正面' logging.info(f'Text: {text}, Result: {result}') return jsonify({'result': result}) except Exception as e: logging.error(f'Error: {e}') return jsonify({'error': str(e)}) if name == 'main': app.run()这个是我的py代码,同一文件夹下,有一个html代码,叫做classify.html,代码如下:<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>BERT文本分类</title> <style> body { font-family: Arial, sans-serif; } h1 { text-align: center; } form { margin: 0 auto; width: 50%; text-align: center; } label { display: block; margin-top: 20px; } input[type="text"] { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; } input[type="submit"] { background-color: #4CAF50; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; } input[type="submit"]:hover { background-color: #45a049; } #result { margin-top: 20px; padding: 10px; border: 1px solid #ccc; border-radius: 4px; background-color: #f2f2f2; } </style> </head> <body> <h1>BERT文本分类</h1> <form> <label for="text">请输入文本:</label> <input type="text" id="text" name="text"> <input type="submit" value="提交"> </form> <div id="result"></div> <script> const form = document.querySelector('form'); const resultDiv = document.querySelector('#result'); form.addEventListener('submit', (event) => { event.preventDefault(); const text = document.querySelector('#text').value; fetch('/classify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({text: text}) }) .then(response => response.json()) .then(data => { resultDiv.innerHTML = <p>分类结果:${data.result}</p>; }) .catch(error => { resultDiv.innerHTML = <p>出错了:${error.message}</p>; }); }); </script> </body> </html>,请问为什么打开后有问题呢,帮我解决一下,优化下代码
时间: 2023-06-17 19:04:05 浏览: 172
python logging.basicConfig不生效的原因及解决
您的 Flask 应用程序需要在主函数中调用 app.run() 才能启动。因此,您可以将以下代码从 if name == 'main': 之前移到其后面:
```
if __name__ == '__main__':
app.run()
```
此外,您需要在 HTML 表单中添加一个 name 属性,以便表单数据能够被正确提取。因此,您需要将输入字段更改为以下内容:
```
<input type="text" id="text" name="text">
```
最后,您需要使用反斜杠(\)将 HTML 字符串拆分为多行,以使其更易于阅读。因此,您需要将以下代码更改为:
```
resultDiv.innerHTML = `<p>分类结果:${data.result}</p>`;
```
完整代码如下:
```
from flask import Flask, request, jsonify
import torch
from transformers import BertTokenizer, BertForSequenceClassification
import logging
app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
tokenizer = BertTokenizer.from_pretrained('bert-base-chinese')
model = BertForSequenceClassification.from_pretrained('bert-base-chinese', num_labels=2)
model.eval()
@app.route('/classify', methods=['POST'])
def classify():
try:
text = request.form['text']
inputs = tokenizer(text, return_tensors='pt')
outputs = model(**inputs)
logits = outputs.logits
probabilities = torch.softmax(logits, dim=1)
predicted_label = torch.argmax(probabilities, dim=1).item()
if predicted_label == 0:
result = '负面'
else:
result = '正面'
logging.info(f'Text: {text}, Result: {result}')
return jsonify({'result': result})
except Exception as e:
logging.error(f'Error: {e}')
return jsonify({'error': str(e)})
if __name__ == '__main__':
app.run()
```
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>BERT文本分类</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
text-align: center;
}
form {
margin: 0 auto;
width: 50%;
text-align: center;
}
label {
display: block;
margin-top: 20px;
}
input[type="text"] {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type="submit"] {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #45a049;
}
#result {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h1>BERT文本分类</h1>
<form>
<label for="text">请输入文本:</label>
<input type="text" id="text" name="text">
<input type="submit" value="提交">
</form>
<div id="result"></div>
<script>
const form = document.querySelector('form');
const resultDiv = document.querySelector('#result');
form.addEventListener('submit', (event) => {
event.preventDefault();
const text = document.querySelector('#text').value;
fetch('/classify', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `text=${text}`
})
.then(response => response.json())
.then(data => {
resultDiv.innerHTML = `<p>分类结果:${data.result}</p>`;
})
.catch(error => {
resultDiv.innerHTML = `<p>出错了:${error.message}</p>`;
});
});
</script>
</body>
</html>
```
阅读全文