Spaces:
Running
Running
from flask import jsonify | |
from main import * | |
import torch | |
def analyze_sentiment(text, output_path="output_sentiment.json"): | |
if sentiment_model is None: | |
return "Sentiment model not initialized." | |
input_tokens = sentiment_model.tokenizer(text, return_tensors="pt", padding=True).to(device) | |
with torch.no_grad(): | |
sentiment_logits = sentiment_model(input_tokens['input_ids']) | |
predicted_class_id = torch.argmax(sentiment_logits, dim=-1).item() | |
sentiment_label = sentiment_model.config.id2label[predicted_class_id] | |
probability = torch.softmax(sentiment_logits, dim=-1)[0][predicted_class_id].item() | |
return {"sentiment": sentiment_label, "probability": probability} | |
def sentiment_api(): | |
data = request.get_json() | |
text = data.get('text') | |
if not text: | |
return jsonify({"error": "Text is required"}), 400 | |
output_file = analyze_sentiment(text) | |
if output_file == "Sentiment model not initialized.": | |
return jsonify({"error": "Sentiment analysis failed"}), 500 | |
return jsonify(output_file) | |