Spaces:
Running
Running
T-Phong
commited on
Commit
·
b0cb70a
1
Parent(s):
5d72cee
update log
Browse files
app.py
CHANGED
|
@@ -1,5 +1,11 @@
|
|
| 1 |
from flask import Flask, request, jsonify
|
| 2 |
from flask_cors import CORS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from model import predict_sentiment_3sentiment, predict_sentiment_5sentiment
|
| 4 |
import pandas as pd
|
| 5 |
|
|
@@ -18,22 +24,29 @@ def predict():
|
|
| 18 |
"""
|
| 19 |
# Lấy dữ liệu JSON từ request
|
| 20 |
json_data = request.get_json()
|
|
|
|
| 21 |
|
| 22 |
# Kiểm tra xem key 'text' có tồn tại và không rỗng không
|
| 23 |
if not json_data or 'text' not in json_data or not json_data.get('text', '').strip():
|
|
|
|
| 24 |
return jsonify({"error": "Vui lòng cung cấp trường 'text' trong request body."}), 400
|
| 25 |
# Kiểm tra xem key 'type' có tồn tại và không rỗng không
|
| 26 |
if not json_data or 'type' not in json_data or not json_data.get('type', '').strip():
|
|
|
|
| 27 |
return jsonify({"error": "Vui lòng cung cấp trường 'type' trong request body."}), 400
|
| 28 |
|
| 29 |
# Lấy văn bản từ dữ liệu
|
| 30 |
text_to_predict = json_data['text']
|
| 31 |
sentiment_type = json_data['type']
|
| 32 |
# Gọi hàm dự đoán từ model
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
# Tạo response
|
| 39 |
response = {
|
|
@@ -57,22 +70,27 @@ def predict_batch():
|
|
| 57 |
"""
|
| 58 |
# 1. Kiểm tra xem có file trong request không
|
| 59 |
if 'file' not in request.files:
|
|
|
|
| 60 |
return jsonify({"error": "Không tìm thấy file trong request (key phải là 'file')."}), 400
|
| 61 |
|
| 62 |
# Dữ liệu form đi kèm với file sẽ nằm trong request.form
|
| 63 |
sentiment_type = request.form.get('type')
|
|
|
|
| 64 |
|
| 65 |
# Kiểm tra xem key 'type' có tồn tại và không rỗng không
|
| 66 |
if not sentiment_type or sentiment_type.strip() not in ["3sentiment", "5sentiment"]:
|
|
|
|
| 67 |
return jsonify({"error": "Vui lòng cung cấp trường 'type' (3sentiment hoặc 5sentiment) trong form data."}), 400
|
| 68 |
file = request.files['file']
|
| 69 |
|
| 70 |
# 2. Kiểm tra xem người dùng có chọn file không
|
| 71 |
if file.filename == '':
|
|
|
|
| 72 |
return jsonify({"error": "Chưa chọn file nào."}), 400
|
| 73 |
|
| 74 |
# 3. Kiểm tra định dạng file
|
| 75 |
if not file.filename.endswith(('.xlsx', '.xls')):
|
|
|
|
| 76 |
return jsonify({"error": "Định dạng file không hợp lệ. Vui lòng sử dụng file .xlsx hoặc .xls."}), 400
|
| 77 |
|
| 78 |
try:
|
|
@@ -96,6 +114,7 @@ def predict_batch():
|
|
| 96 |
|
| 97 |
return jsonify(results)
|
| 98 |
except Exception as e:
|
|
|
|
| 99 |
return jsonify({"error": f"Đã xảy ra lỗi khi xử lý file: {str(e)}"}), 500
|
| 100 |
|
| 101 |
if __name__ == "__main__":
|
|
|
|
| 1 |
from flask import Flask, request, jsonify
|
| 2 |
from flask_cors import CORS
|
| 3 |
+
import logging
|
| 4 |
+
|
| 5 |
+
# Cấu hình logging cho app
|
| 6 |
+
logging.basicConfig(level=logging.INFO)
|
| 7 |
+
logger = logging.getLogger(__name__)
|
| 8 |
+
|
| 9 |
from model import predict_sentiment_3sentiment, predict_sentiment_5sentiment
|
| 10 |
import pandas as pd
|
| 11 |
|
|
|
|
| 24 |
"""
|
| 25 |
# Lấy dữ liệu JSON từ request
|
| 26 |
json_data = request.get_json()
|
| 27 |
+
logger.info(f"Received predict request: {json_data}")
|
| 28 |
|
| 29 |
# Kiểm tra xem key 'text' có tồn tại và không rỗng không
|
| 30 |
if not json_data or 'text' not in json_data or not json_data.get('text', '').strip():
|
| 31 |
+
logger.warning("Missing 'text' in request")
|
| 32 |
return jsonify({"error": "Vui lòng cung cấp trường 'text' trong request body."}), 400
|
| 33 |
# Kiểm tra xem key 'type' có tồn tại và không rỗng không
|
| 34 |
if not json_data or 'type' not in json_data or not json_data.get('type', '').strip():
|
| 35 |
+
logger.warning("Missing 'type' in request")
|
| 36 |
return jsonify({"error": "Vui lòng cung cấp trường 'type' trong request body."}), 400
|
| 37 |
|
| 38 |
# Lấy văn bản từ dữ liệu
|
| 39 |
text_to_predict = json_data['text']
|
| 40 |
sentiment_type = json_data['type']
|
| 41 |
# Gọi hàm dự đoán từ model
|
| 42 |
+
try:
|
| 43 |
+
if sentiment_type == "3sentiment":
|
| 44 |
+
sentiment, score = predict_sentiment_3sentiment(text_to_predict)
|
| 45 |
+
elif sentiment_type == "5sentiment":
|
| 46 |
+
sentiment, score = predict_sentiment_5sentiment(text_to_predict)
|
| 47 |
+
except Exception as e:
|
| 48 |
+
logger.error(f"Prediction error: {e}")
|
| 49 |
+
return jsonify({"error": str(e)}), 500
|
| 50 |
|
| 51 |
# Tạo response
|
| 52 |
response = {
|
|
|
|
| 70 |
"""
|
| 71 |
# 1. Kiểm tra xem có file trong request không
|
| 72 |
if 'file' not in request.files:
|
| 73 |
+
logger.warning("No file part in request")
|
| 74 |
return jsonify({"error": "Không tìm thấy file trong request (key phải là 'file')."}), 400
|
| 75 |
|
| 76 |
# Dữ liệu form đi kèm với file sẽ nằm trong request.form
|
| 77 |
sentiment_type = request.form.get('type')
|
| 78 |
+
logger.info(f"Received batch predict request for type: {sentiment_type}")
|
| 79 |
|
| 80 |
# Kiểm tra xem key 'type' có tồn tại và không rỗng không
|
| 81 |
if not sentiment_type or sentiment_type.strip() not in ["3sentiment", "5sentiment"]:
|
| 82 |
+
logger.warning("Invalid or missing 'type'")
|
| 83 |
return jsonify({"error": "Vui lòng cung cấp trường 'type' (3sentiment hoặc 5sentiment) trong form data."}), 400
|
| 84 |
file = request.files['file']
|
| 85 |
|
| 86 |
# 2. Kiểm tra xem người dùng có chọn file không
|
| 87 |
if file.filename == '':
|
| 88 |
+
logger.warning("No selected file")
|
| 89 |
return jsonify({"error": "Chưa chọn file nào."}), 400
|
| 90 |
|
| 91 |
# 3. Kiểm tra định dạng file
|
| 92 |
if not file.filename.endswith(('.xlsx', '.xls')):
|
| 93 |
+
logger.warning(f"Invalid file format: {file.filename}")
|
| 94 |
return jsonify({"error": "Định dạng file không hợp lệ. Vui lòng sử dụng file .xlsx hoặc .xls."}), 400
|
| 95 |
|
| 96 |
try:
|
|
|
|
| 114 |
|
| 115 |
return jsonify(results)
|
| 116 |
except Exception as e:
|
| 117 |
+
logger.error(f"Error processing batch file: {e}")
|
| 118 |
return jsonify({"error": f"Đã xảy ra lỗi khi xử lý file: {str(e)}"}), 500
|
| 119 |
|
| 120 |
if __name__ == "__main__":
|
model.py
CHANGED
|
@@ -3,18 +3,36 @@
|
|
| 3 |
import torch
|
| 4 |
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 5 |
import torch.nn.functional as F
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
model_name_3sentiment = "phongnt251199/phobert-sentiment-reviews-v5"
|
| 8 |
model_name_5sentiment = "phongnt251199/phobert-sentiment-reviews-v4"
|
| 9 |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
|
|
|
| 10 |
|
| 11 |
# Load tokenizer và model cho 3 nhãn
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
# Load tokenizer và model như bình thườngclear
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
def predict_sentiment_3sentiment(text):
|
| 20 |
inputs = tokenizer_3sentiment(text, padding=True, truncation=True, max_length=256, return_tensors="pt").to(device)
|
|
|
|
| 3 |
import torch
|
| 4 |
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 5 |
import torch.nn.functional as F
|
| 6 |
+
import logging
|
| 7 |
+
|
| 8 |
+
# Cấu hình logging
|
| 9 |
+
logging.basicConfig(level=logging.INFO)
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
|
| 12 |
model_name_3sentiment = "phongnt251199/phobert-sentiment-reviews-v5"
|
| 13 |
model_name_5sentiment = "phongnt251199/phobert-sentiment-reviews-v4"
|
| 14 |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 15 |
+
logger.info(f"Device being used: {device}")
|
| 16 |
|
| 17 |
# Load tokenizer và model cho 3 nhãn
|
| 18 |
+
logger.info(f"Start loading model 3sentiment: {model_name_3sentiment}")
|
| 19 |
+
try:
|
| 20 |
+
tokenizer_3sentiment = AutoTokenizer.from_pretrained(model_name_3sentiment)
|
| 21 |
+
model_3sentiment = AutoModelForSequenceClassification.from_pretrained(model_name_3sentiment, num_labels=3).to(device)
|
| 22 |
+
logger.info("Loaded model 3sentiment successfully")
|
| 23 |
+
except Exception as e:
|
| 24 |
+
logger.error(f"Error loading model 3sentiment: {e}")
|
| 25 |
+
raise e
|
| 26 |
|
| 27 |
# Load tokenizer và model như bình thườngclear
|
| 28 |
+
logger.info(f"Start loading model 5sentiment: {model_name_5sentiment}")
|
| 29 |
+
try:
|
| 30 |
+
tokenizer_5sentiment = AutoTokenizer.from_pretrained(model_name_5sentiment)
|
| 31 |
+
model_5sentiment = AutoModelForSequenceClassification.from_pretrained(model_name_5sentiment, num_labels=5).to(device)
|
| 32 |
+
logger.info("Loaded model 5sentiment successfully")
|
| 33 |
+
except Exception as e:
|
| 34 |
+
logger.error(f"Error loading model 5sentiment: {e}")
|
| 35 |
+
raise e
|
| 36 |
|
| 37 |
def predict_sentiment_3sentiment(text):
|
| 38 |
inputs = tokenizer_3sentiment(text, padding=True, truncation=True, max_length=256, return_tensors="pt").to(device)
|