File size: 4,821 Bytes
fcb8cc9
 
 
 
 
 
 
 
 
6cfdd4c
fcb8cc9
45cf1af
6cfdd4c
 
 
 
249726c
fcb8cc9
 
 
 
6cfdd4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf5b03b
 
 
6cfdd4c
 
 
cf5b03b
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
from flask import Flask, request, render_template_string, jsonify, send_from_directory
import requests
import pandas as pd
import re
import time
from random import randint, choice
import os
from transformers import XLMRobertaForSequenceClassification, XLMRobertaTokenizer
from peft import PeftModel, PeftConfig  # Ensure peft library is installed
import torch
from collections import defaultdict


# Define the Flask app
flask_app = Flask(__name__)

 #Load the base XLM-RoBERTa model with the correct number of labels (3 labels for classification)
tokenizer = XLMRobertaTokenizer.from_pretrained("letijo03/lora-adapter-32",use_fast=True, trust_remote_code=True)
base_model = XLMRobertaForSequenceClassification.from_pretrained("xlm-roberta-base", num_labels=3)
config = PeftConfig.from_pretrained("letijo03/lora-adapter-32")
model = PeftModel.from_pretrained(base_model, "letijo03/lora-adapter-32")
model.eval()  # Set the model to evaluation mode

def classify_sentiment(text):
    inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512)
    outputs = model(**inputs)
    prediction = torch.argmax(outputs.logits, dim=-1)
    return prediction.item()

# HTML template for user input
html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Comment Sentiment Analysis</title>
  <style>
    body { font-family: Arial, sans-serif; background-color: #f5f5f5; margin: 0; padding: 0; color: #333; }
    header { background-color: #FF5722; color: white; padding: 20px; text-align: center; }
    main { padding: 20px; max-width: 900px; margin: 0 auto; background-color: white; border-radius: 8px; box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1); }
    form { margin: 20px auto; max-width: 600px; display: flex; flex-direction: column; gap: 15px; background-color: #f9f9f9; padding: 20px; border-radius: 8px; box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1); }
    textarea, button { padding: 12px; font-size: 1.1em; border: 1px solid #ccc; border-radius: 6px; }
    textarea { background-color: #fff; resize: vertical; min-height: 100px; }
    button { background-color: #FF5722; color: white; border: none; cursor: pointer; transition: background-color 0.3s ease; }
    button:hover { background-color: #E64A19; }
    .result-message { text-align: center; margin-top: 20px; font-size: 18px; font-weight: bold; }
  </style>
  <script>
    document.addEventListener("DOMContentLoaded", function() {
      document.getElementById("commentForm").onsubmit = async function(e) {
        e.preventDefault();
        const comment = document.getElementById("comment").value;
        const resultDiv = document.getElementById("result");
        resultDiv.innerHTML = "";
        try {
          const response = await fetch('/analyze', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({ 'comment': comment })
          });
          const data = await response.json();
          if (data.error) {
            resultDiv.innerHTML = `<p class="result-message" style="color:red;">${data.error}</p>`;
          } else {
            resultDiv.innerHTML = `<p class="result-message" style="color:green;">${data.message}</p>`;
          }
        } catch (error) {
          resultDiv.innerHTML = `<p class="result-message" style="color:red;">Error sending request: ${error.message}</p>`;
          console.error('Fetch error:', error);
        }
      };
    });
  </script>
</head>
<body>
  <header>
    <h1>Comment Sentiment Analysis</h1>
  </header>
  <main>
    <form id="commentForm">
      <label for="comment">Enter your comment:</label>
      <textarea id="comment" name="comment" placeholder="Type your comment here..." required></textarea>
      <button type="submit">Analyze Sentiment</button>
    </form>
    <div id="result"></div>
  </main>
</body>
</html>
"""

@flask_app.route('/')
def index():
    return render_template_string(html_template)

@flask_app.route('/analyze', methods=['POST'])
def analyze():
    comment = request.form.get('comment')
    if not comment or comment.strip() == "":
        return jsonify({'error': 'Please provide a valid comment.'})
    sentiment = classify_sentiment(comment)
    sentiment_label = "Positive" if sentiment == 2 else "Neutral" if sentiment == 1 else "Negative"
    return jsonify({'message': f'Sentiment analysis complete. The sentiment is: {sentiment_label}.'})

# Wrap the Flask app as an ASGI app so that the module-level variable 'app' is ASGI-compatible
from asgiref.wsgi import WsgiToAsgi
app = WsgiToAsgi(flask_app)

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))