T-Phong commited on
Commit
0d7a9c0
·
0 Parent(s):

Initial commit

Browse files
Files changed (5) hide show
  1. .gitignore +23 -0
  2. api.py +103 -0
  3. app.py +0 -0
  4. model.py +42 -0
  5. requirements.txt +5 -0
.gitignore ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ build/
11
+ dist/
12
+ *.egg-info/
13
+
14
+ # Virtual Environments
15
+ .env
16
+ .venv
17
+ env/
18
+ venv/
19
+
20
+ # Hugging Face cache
21
+ # Các model được tải từ Hub, không cần lưu trữ trong git
22
+ .cache/
23
+ huggingface/
api.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
2
+ from model.model import predict_sentiment_3sentiment, predict_sentiment_5sentiment
3
+ import pandas as pd
4
+
5
+ # Khởi tạo Flask app
6
+ app = Flask(__name__)
7
+
8
+ # Xử lý encoding cho tiếng Việt để hiển thị đúng trong response
9
+ app.config['JSON_AS_ASCII'] = False
10
+
11
+ @app.route("/predict", methods=['POST'])
12
+ def predict():
13
+ """
14
+ Dự đoán cảm xúc từ văn bản đầu vào.
15
+ Request body phải là JSON có dạng: {"text": "nội dung bình luận"}
16
+ """
17
+ # Lấy dữ liệu JSON từ request
18
+ json_data = request.get_json()
19
+
20
+ # Kiểm tra xem key 'text' có tồn tại và không rỗng không
21
+ if not json_data or 'text' not in json_data or not json_data.get('text', '').strip():
22
+ return jsonify({"error": "Vui lòng cung cấp trường 'text' trong request body."}), 400
23
+ # Kiểm tra xem key 'type' có tồn tại và không rỗng không
24
+ if not json_data or 'type' not in json_data or not json_data.get('type', '').strip():
25
+ return jsonify({"error": "Vui lòng cung cấp trường 'type' trong request body."}), 400
26
+
27
+ # Lấy văn bản từ dữ liệu
28
+ text_to_predict = json_data['text']
29
+ sentiment_type = json_data['type']
30
+ # Gọi hàm dự đoán từ model
31
+ if sentiment_type == "3sentiment":
32
+ sentiment, score = predict_sentiment_3sentiment(text_to_predict)
33
+ elif sentiment_type == "5sentiment":
34
+ sentiment, score = predict_sentiment_5sentiment(text_to_predict)
35
+
36
+ # Tạo response
37
+ response = {
38
+ "comment": text_to_predict,
39
+ "sentiment": sentiment,
40
+ "confidence": score
41
+ }
42
+
43
+ return jsonify(response)
44
+
45
+ @app.route("/")
46
+ def read_root():
47
+ return jsonify({"message": "Chào mừng đến với API Phân tích Cảm xúc sử dụng Flask!"})
48
+
49
+ @app.route("/predict-batch", methods=['POST'])
50
+ def predict_batch():
51
+ """
52
+ Dự đoán cảm xúc cho một loạt bình luận từ file Excel.
53
+ File Excel phải được gửi dưới dạng form-data với key là 'file'.
54
+ Cột đầu tiên của file Excel sẽ được sử dụng làm cột chứa bình luận.
55
+ """
56
+ # 1. Kiểm tra xem có file trong request không
57
+ if 'file' not in request.files:
58
+ return jsonify({"error": "Không tìm thấy file trong request (key phải là 'file')."}), 400
59
+
60
+ # Dữ liệu form đi kèm với file sẽ nằm trong request.form
61
+ sentiment_type = request.form.get('type')
62
+
63
+ # Kiểm tra xem key 'type' có tồn tại và không rỗng không
64
+ if not sentiment_type or sentiment_type.strip() not in ["3sentiment", "5sentiment"]:
65
+ return jsonify({"error": "Vui lòng cung cấp trường 'type' (3sentiment hoặc 5sentiment) trong form data."}), 400
66
+ file = request.files['file']
67
+
68
+ # 2. Kiểm tra xem người dùng có chọn file không
69
+ if file.filename == '':
70
+ return jsonify({"error": "Chưa chọn file nào."}), 400
71
+
72
+ # 3. Kiểm tra định dạng file
73
+ if not file.filename.endswith(('.xlsx', '.xls')):
74
+ return jsonify({"error": "Định dạng file không hợp lệ. Vui lòng sử dụng file .xlsx hoặc .xls."}), 400
75
+
76
+ try:
77
+ # 4. Đọc file Excel bằng pandas, sử dụng engine openpyxl
78
+ df = pd.read_excel(file, engine='openpyxl')
79
+
80
+ if df.empty:
81
+ return jsonify({"error": "File Excel rỗng."}), 400
82
+
83
+ # Lấy tên cột đầu tiên để xử lý
84
+ comments_column = df.columns[0]
85
+
86
+ results = []
87
+ # 5. Lặp qua từng bình luận (bỏ qua các dòng rỗng) để dự đoán
88
+ for comment in df[comments_column].dropna().astype(str):
89
+ if sentiment_type == "3sentiment":
90
+ sentiment, score = predict_sentiment_3sentiment(comment)
91
+ elif sentiment_type == "5sentiment":
92
+ sentiment, score = predict_sentiment_5sentiment(comment)
93
+ results.append({"comment": comment, "sentiment": sentiment, "confidence": score})
94
+
95
+ return jsonify(results)
96
+ except Exception as e:
97
+ return jsonify({"error": f"Đã xảy ra lỗi khi xử lý file: {str(e)}"}), 500
98
+
99
+ if __name__ == "__main__":
100
+ # Chạy app ở chế độ debug để tự động reload khi có thay đổi
101
+ # host='0.0.0.0' để có thể truy cập từ bên ngoài network
102
+ # Lưu ý: Không sử dụng debug=True trong môi trường production
103
+ app.run(host="0.0.0.0", port=8000, debug=True)
app.py ADDED
File without changes
model.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Thay bằng repo_id bạn đã tạo ở trên
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-v3"
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
+ tokenizer_3sentiment = AutoTokenizer.from_pretrained(model_name_3sentiment)
13
+ model_3sentiment = AutoModelForSequenceClassification.from_pretrained(model_name_3sentiment, num_labels=3).to(device)
14
+
15
+ # Load tokenizer và model như bình thườngclear
16
+ tokenizer_5sentiment = AutoTokenizer.from_pretrained(model_name_5sentiment)
17
+ model_5sentiment = AutoModelForSequenceClassification.from_pretrained(model_name_5sentiment, num_labels=5).to(device)
18
+
19
+ def predict_sentiment_3sentiment(text):
20
+ inputs = tokenizer_3sentiment(text, padding=True, truncation=True, max_length=256, return_tensors="pt").to(device)
21
+ with torch.no_grad():
22
+ outputs = model_3sentiment(**inputs)
23
+ probs = outputs.logits.softmax(dim=1)
24
+ pred_label = torch.argmax(probs, dim=1).item()
25
+ # Dòng sau dùng để debug, có thể xóa hoặc comment lại
26
+ # probs_point = F.softmax(outputs.logits, dim=1)
27
+ # print(probs_point[0])
28
+ #labels_map = {0: 'Rất tệ', 1: 'Tệ', 2: 'Bình thường', 3: 'Khá tốt', 4: 'Rất tốt'}
29
+ labels_map = {0: 'Tiêu cực', 1: 'Bình thường', 2: 'Tích cực'}
30
+ return labels_map[pred_label], probs[0][pred_label].item()
31
+
32
+ def predict_sentiment_5sentiment(text):
33
+ inputs = tokenizer_5sentiment(text, padding=True, truncation=True, max_length=256, return_tensors="pt").to(device)
34
+ with torch.no_grad():
35
+ outputs = model_5sentiment(**inputs)
36
+ probs = outputs.logits.softmax(dim=1)
37
+ pred_label = torch.argmax(probs, dim=1).item()
38
+ # Dòng sau dùng để debug, có thể xóa hoặc comment lại
39
+ # probs_point = F.softmax(outputs.logits, dim=1)
40
+ # print(probs_point[0])
41
+ labels_map = {0: 'Rất tệ (1 sao)', 1: 'Tệ (2 sao)', 2: 'Bình thường (3 sao)', 3: 'Khá tốt (4 sao)', 4: 'Rất tốt (5 sao)'}
42
+ return labels_map[pred_label], probs[0][pred_label].item()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ transformers
2
+ torch
3
+ flask
4
+ pandas
5
+ openpyxl