File size: 744 Bytes
1c817fd
 
 
 
e83e49f
7b74407
 
 
e83e49f
7b74407
e83e49f
1c817fd
7b74407
e83e49f
7b74407
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from flask import jsonify
from main import *
import torch

def analyze_sentiment(text):
    if sentiment_model is None: return {"error": "Sentiment model not initialized."}
    features = [ord(c) for c in text[:10]]; 
    while len(features) < 10: features.append(0)
    features_tensor = torch.tensor(features, dtype=torch.float32).unsqueeze(0).to(device)
    with torch.no_grad(): output = sentiment_model(features_tensor); sentiment_idx = torch.argmax(output, dim=1).item(); sentiment_label = "positive" if sentiment_idx == 1 else "negative"
    return {"sentiment": sentiment_label}

def sentiment_api(text):
    output = analyze_sentiment(text)
    if "error" in output: return {"error": output["error"]}
    return output