File size: 4,053 Bytes
d9c57c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import os
from flask import send_file
# πŸ‘‡ Set huggingface cache directory to a writable path in Spaces
os.environ["HF_HOME"] = "/tmp"
from flask import Flask, render_template, request, redirect
import pandas as pd
from predictor import predict_sentiment

app = Flask(__name__)

# πŸ”˜ Label mapping
LABEL_MAP = {
    "LABEL_0": "Negative",
    "LABEL_1": "Positive"
}

# πŸ”˜ Root β†’ redirect to single review page
@app.route("/")
def root():
    return redirect("/sentiment-review/single")

# πŸ”˜ Single review input route
@app.route("/sentiment-review/single", methods=["GET", "POST"])
def single_review():
    prediction = None
    confidence = None
    review = ""
    chosen_model = None

    if request.method == "POST":
        review = request.form.get("review", "").strip()
        if review:
            try:
                result = predict_sentiment(review)

                raw_label = result["prediction"].get("label")
                score = result["prediction"].get("score", 0.0)
                chosen_model = result.get("chosen_model", "N/A")

                prediction = LABEL_MAP.get(raw_label, raw_label)
                confidence = round(float(score) * 100, 2)

            except Exception as e:
                print("❌ Single Review Processing Error:", e)
                prediction = "Error"
                confidence = 0.0
                chosen_model = "N/A"

    return render_template(
        "index.html",
        prediction=prediction,
        confidence=confidence,
        review=review,
        chosen_model=chosen_model
    )

# πŸ“ Batch upload route
@app.route("/sentiment-review/batch", methods=["GET", "POST"])
def batch_review():
    if request.method == "POST":
        if 'csvfile' not in request.files:
            return render_template("batch.html", error="No file part found.")

        file = request.files['csvfile']
        if not file.filename:
            return render_template("batch.html", error="No selected file.")

        if file and file.filename.endswith(".csv"):
            try:
                df = pd.read_csv(file, encoding="utf-8")
                if "review" not in df.columns:
                    return render_template("batch.html", error="CSV must have a 'review' column.")

                results = []
                for i, text in enumerate(df["review"].fillna("").tolist()):
                    try:
                        result = predict_sentiment(text)

                        raw_label = result["prediction"].get("label")
                        score = result["prediction"].get("score", 0.0)
                        chosen_model = result.get("chosen_model", "N/A")

                        sentiment = LABEL_MAP.get(raw_label, raw_label)
                        confidence = round(float(score) * 100, 2)

                        print(f"🧠 Review {i+1}: {text[:40]}... β†’ {sentiment} ({confidence}%) [Model: {chosen_model}]")

                        results.append({
                            "text": text,
                            "sentiment": sentiment,
                            "confidence": confidence,
                            "chosen_model": chosen_model
                        })
                    except Exception as inner_e:
                        print(f"⚠️ Error processing review {i+1}: {inner_e}")
                        results.append({
                            "text": text,
                            "sentiment": "Error",
                            "confidence": 0.0,
                            "chosen_model": "N/A"
                        })

                return render_template("batch.html", results=results)

            except Exception as e:
                print("❌ CSV Processing error:", e)
                return render_template("batch.html", error=f"Processing error: {str(e)}")

        return render_template("batch.html", error="Invalid file format. Upload .csv only.")

    return render_template("batch.html")


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=7860, debug=True)