AbdoIR commited on
Commit
8df4c2d
·
verified ·
1 Parent(s): a5013d1

Upload 7 files

Browse files
api.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, send_file, jsonify
2
+ from transformers import DistilBertForSequenceClassification, DistilBertTokenizer
3
+ import pandas as pd
4
+ import torch
5
+ import tempfile
6
+ import os
7
+ import re
8
+ from collections import Counter
9
+ from flask_cors import CORS
10
+
11
+ app = Flask(__name__)
12
+ CORS(app)
13
+
14
+ # Load model from Hugging Face Hub
15
+ model_name = "AbdoIR/x-sentiment-analysis"
16
+ model = DistilBertForSequenceClassification.from_pretrained(model_name)
17
+ tokenizer = DistilBertTokenizer.from_pretrained(model_name)
18
+
19
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
20
+ model.to(device)
21
+ model.eval()
22
+
23
+ # Predict sentiment
24
+ def predict_sentiment(texts):
25
+ encodings = tokenizer(texts, truncation=True, padding=True, max_length=128, return_tensors="pt")
26
+ encodings = {key: val.to(device) for key, val in encodings.items()}
27
+ with torch.no_grad():
28
+ outputs = model(**encodings)
29
+ predictions = torch.argmax(outputs.logits, dim=1)
30
+ sentiment_map = {0: "Negative", 1: "Neutral", 2: "Positive"}
31
+ return [sentiment_map[p.item()] for p in predictions]
32
+
33
+ # Top frequent words
34
+ def get_top_words(texts, n=30):
35
+ all_words = []
36
+ for text in texts:
37
+ tokens = re.findall(r'\b\w{3,}\b', str(text).lower())
38
+ all_words.extend(tokens)
39
+ counter = Counter(all_words)
40
+ most_common = counter.most_common(n)
41
+ return pd.DataFrame(most_common, columns=['word', 'count'])
42
+
43
+ # POST /predict
44
+ @app.route('/predict', methods=['POST'])
45
+ def predict():
46
+ if 'file' not in request.files:
47
+ return jsonify({'error': 'No file uploaded'}), 400
48
+
49
+ file = request.files['file']
50
+ try:
51
+ df = pd.read_csv(file)
52
+ except Exception:
53
+ try:
54
+ file.seek(0)
55
+ df = pd.read_excel(file)
56
+ except Exception:
57
+ return jsonify({'error': 'Unable to read the file'}), 400
58
+
59
+ if 'content' in df.columns:
60
+ text_col = 'content'
61
+ elif 'tweet' in df.columns:
62
+ text_col = 'tweet'
63
+ else:
64
+ return jsonify({'error': 'No "content" or "tweet" column found'}), 400
65
+
66
+ texts = df[text_col].astype(str).tolist()
67
+ df['sentiment'] = predict_sentiment(texts)
68
+
69
+ top_words_df = get_top_words(texts)
70
+
71
+ temp_dir = tempfile.mkdtemp()
72
+
73
+ sentiment_path = os.path.join(temp_dir, 'final_data.csv')
74
+ df.to_csv(sentiment_path, index=False)
75
+
76
+ words_path = os.path.join(temp_dir, 'word_frequent.csv')
77
+ top_words_df.to_csv(words_path, index=False)
78
+
79
+ return jsonify({
80
+ 'sentiment_file': f'/download?file={sentiment_path}',
81
+ 'top_words_file': f'/download?file={words_path}',
82
+ 'sentiment_data': df.to_dict(orient='records'),
83
+ 'top_words_data': top_words_df.to_dict(orient='records')
84
+ })
85
+
86
+ # GET /download
87
+ @app.route('/download')
88
+ def download():
89
+ file_path = request.args.get('file')
90
+ if not file_path or not os.path.exists(file_path):
91
+ return jsonify({'error': 'File not found'}), 404
92
+ return send_file(file_path, as_attachment=True)
93
+
94
+ if __name__ == '__main__':
95
+ app.run(host="0.0.0.0", port=5000, debug=True)
fine_tuned_model/config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation": "gelu",
3
+ "architectures": [
4
+ "DistilBertForSequenceClassification"
5
+ ],
6
+ "attention_dropout": 0.1,
7
+ "dim": 768,
8
+ "dropout": 0.1,
9
+ "hidden_dim": 3072,
10
+ "id2label": {
11
+ "0": "LABEL_0",
12
+ "1": "LABEL_1",
13
+ "2": "LABEL_2"
14
+ },
15
+ "initializer_range": 0.02,
16
+ "label2id": {
17
+ "LABEL_0": 0,
18
+ "LABEL_1": 1,
19
+ "LABEL_2": 2
20
+ },
21
+ "max_position_embeddings": 512,
22
+ "model_type": "distilbert",
23
+ "n_heads": 12,
24
+ "n_layers": 6,
25
+ "pad_token_id": 0,
26
+ "problem_type": "single_label_classification",
27
+ "qa_dropout": 0.1,
28
+ "seq_classif_dropout": 0.2,
29
+ "sinusoidal_pos_embds": false,
30
+ "tie_weights_": true,
31
+ "torch_dtype": "float32",
32
+ "transformers_version": "4.51.3",
33
+ "vocab_size": 30522
34
+ }
fine_tuned_model/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ba23b5ee5a6081da5cca7705f3ebe7acad7664f4ea8b9175da8d2f1c2a7d74cf
3
+ size 267835644
fine_tuned_model/special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
fine_tuned_model/tokenizer_config.json ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": true,
45
+ "cls_token": "[CLS]",
46
+ "do_basic_tokenize": true,
47
+ "do_lower_case": true,
48
+ "extra_special_tokens": {},
49
+ "mask_token": "[MASK]",
50
+ "model_max_length": 512,
51
+ "never_split": null,
52
+ "pad_token": "[PAD]",
53
+ "sep_token": "[SEP]",
54
+ "strip_accents": null,
55
+ "tokenize_chinese_chars": true,
56
+ "tokenizer_class": "DistilBertTokenizer",
57
+ "unk_token": "[UNK]"
58
+ }
fine_tuned_model/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ flask
2
+ flask-cors
3
+ torch
4
+ transformers
5
+ pandas
6
+ openpyxl
7
+ gunicorn