Update api.py
Browse files
api.py
CHANGED
|
@@ -1,95 +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)
|
|
|
|
| 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/fine_tuned_model"
|
| 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)
|