File size: 957 Bytes
1c817fd
 
 
 
e83e49f
1c817fd
e83e49f
 
 
 
 
 
1c817fd
 
e83e49f
 
 
1c817fd
e83e49f
1c817fd
 
 
 
 
 
e83e49f
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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():
    data = request.get_json()
    text = data.get('text')
    if not text:
        return jsonify({"error": "Text is required"}), 400
    output = analyze_sentiment(text)
    if "error" in output:
        return jsonify({"error": output["error"]}), 500
    return jsonify(output)