rup69 commited on
Commit
68fa62c
·
verified ·
1 Parent(s): 3d49e76

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -149
app.py CHANGED
@@ -1,150 +1,149 @@
1
- import gradio as gr
2
- from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
- import torch
4
- import json
5
- import os
6
-
7
- # --- 1. CONFIGURATION ---
8
- MODEL_PATH = "."
9
- LABELS = ["anger", "fear", "joy", "sadness", "surprise"]
10
- DEFAULT_THRESHOLDS = {"anger": 0.5, "fear": 0.5, "joy": 0.5, "sadness": 0.5, "surprise": 0.5}
11
-
12
- # --- 2. LOAD RESOURCES ---
13
- # Load Model
14
- try:
15
- model = AutoModelForSequenceClassification.from_pretrained(MODEL_PATH)
16
- # Check if safe tensors actually exist
17
- if not os.path.exists(os.path.join(MODEL_PATH, "model.safetensors")):
18
- raise FileNotFoundError
19
- except:
20
- model = None # Fallback
21
-
22
- # Load Tokenizer
23
- try:
24
- tokenizer = AutoTokenizer.from_pretrained("roberta-large")
25
- except:
26
- tokenizer = AutoTokenizer.from_pretrained("roberta-base")
27
-
28
- # Load Thresholds
29
- if os.path.exists("fine_thresholds.json"):
30
- with open("fine_thresholds.json", "r") as f:
31
- THRESHOLDS = json.load(f)
32
- else:
33
- THRESHOLDS = DEFAULT_THRESHOLDS
34
-
35
- # --- 3. LOGIC ---
36
- def analyze(text):
37
- if not text or not text.strip():
38
- return {}, "⚠️ Please type something first!"
39
- if model is None:
40
- return {}, "⚠️ Model files missing in this folder."
41
-
42
- inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
43
- model.eval()
44
- with torch.no_grad():
45
- outputs = model(**inputs)
46
- probs = torch.sigmoid(outputs.logits).numpy()[0]
47
-
48
- results = {}
49
- detected_emotions = []
50
-
51
- for i, label in enumerate(LABELS):
52
- score = float(probs[i])
53
- results[label] = score
54
- if score > THRESHOLDS.get(label, 0.5):
55
- detected_emotions.append(label.upper())
56
-
57
- if not detected_emotions:
58
- final_verdict = "😐 No strong emotion detected."
59
- else:
60
- final_verdict = " ".join([f"**{e}**" for e in detected_emotions])
61
-
62
- return results, final_verdict
63
-
64
- # --- 4. PROFESSIONAL CSS (The "Form" Look) ---
65
- custom_css = """
66
- /* 1. Background Gradient */
67
- .gradio-container {
68
- background: linear-gradient(135deg, #e0e7ff 0%, #f3f4f6 100%) !important;
69
- }
70
-
71
- /* 2. The White Card Container */
72
- .form-card {
73
- max-width:600px;
74
- margin:auto;
75
- background: white !important;
76
- border-radius: 12px !important;
77
- padding: 30px !important;
78
- box-shadow: 0 10px 30px rgba(0,0,0,0.1) !important;
79
- border-top: 6px solid #6366f1 !important; /* Indigo Top Bar */
80
- border: 1px solid #e5e7eb !important;
81
- }
82
-
83
- /* 3. Header Text */
84
- .form-header h1 {
85
- color: #4338ca;
86
- text-align: center;
87
- font-weight: 800;
88
- margin-bottom: 5px;
89
- }
90
- .form-header p {
91
- color: #6b7280;
92
- text-align: center;
93
- margin-bottom: 20px;
94
- }
95
-
96
- /* 4. Button Styling */
97
- button.primary {
98
- background: #4f46e5 !important;
99
- font-size: 1.1em !important;
100
- }
101
- """
102
-
103
- # --- 5. UI LAYOUT ---
104
- theme = gr.themes.Base(primary_hue="indigo", font=[gr.themes.GoogleFont("Inter"), "system-ui"])
105
-
106
- with gr.Blocks( title="Sentiment Check") as app:
107
-
108
- # We wrap everything in a Column with our custom 'form-card' class
109
- with gr.Column(elem_classes="form-card"):
110
-
111
- # Header
112
- gr.HTML("""
113
- <div class="form-header">
114
- <h1>🧠 Sentiment Check</h1>
115
- <p>Advanced Neural Emotion Detection System</p>
116
- </div>
117
- """)
118
-
119
- # Section 1: Input
120
- gr.Markdown("### 1. Source Text")
121
- txt_input = gr.Textbox(
122
- lines=4,
123
- placeholder="Type your text here...",
124
- show_label=False,
125
- container=False # Makes it look cleaner
126
- )
127
-
128
- # Action Button
129
- btn_run = gr.Button("GENERATE REPORT", variant="primary", size="lg")
130
-
131
- # Divider
132
- gr.HTML("<hr style='margin: 20px 0; border: 0; border-top: 1px solid #e5e7eb;'>")
133
-
134
- # Section 2: Results
135
- gr.Markdown("### 2. Analysis Results")
136
- with gr.Row():
137
- with gr.Column(scale=1):
138
- lbl_verdict = gr.Markdown("**Status:** Waiting for data...", label="Prediction")
139
- with gr.Column(scale=1):
140
- lbl_chart = gr.Label(num_top_classes=5, label="Confidence Spectrum")
141
-
142
- # Footer
143
- gr.Markdown(
144
- "<div style='text-align:center; color:#9ca3af; margin-top:15px; font-size:0.8em;'>Secure Local Deployment • Powered by RoBERTa</div>"
145
- )
146
-
147
- # Logic
148
- btn_run.click(fn=analyze, inputs=txt_input, outputs=[lbl_chart, lbl_verdict])
149
-
150
  app.launch(theme=theme, css=custom_css,share=False)#,auth=("admin", "pass123"))
 
1
+ import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
+ import torch
4
+ import json
5
+ import os
6
+
7
+ # --- 1. CONFIGURATION ---
8
+ MODEL_PATH = "rup69/Sentiment-Analysis"
9
+ LABELS = ["anger", "fear", "joy", "sadness", "surprise"]
10
+ DEFAULT_THRESHOLDS = {"anger": 0.5, "fear": 0.5, "joy": 0.5, "sadness": 0.5, "surprise": 0.5}
11
+
12
+ # --- 2. LOAD RESOURCES ---
13
+ # Load Model
14
+ ry:
15
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_PATH)
16
+ print("✅ Model loaded from Model Repo!")
17
+ except Exception as e:
18
+ model = None
19
+ print(f"❌ Error loading model: {e}")
20
+
21
+ # Load Tokenizer
22
+ try:
23
+ tokenizer = AutoTokenizer.from_pretrained("roberta-large")
24
+ except:
25
+ tokenizer = AutoTokenizer.from_pretrained("roberta-base")
26
+
27
+ # Load Thresholds
28
+ if os.path.exists("fine_thresholds.json"):
29
+ with open("fine_thresholds.json", "r") as f:
30
+ THRESHOLDS = json.load(f)
31
+ else:
32
+ THRESHOLDS = DEFAULT_THRESHOLDS
33
+
34
+ # --- 3. LOGIC ---
35
+ def analyze(text):
36
+ if not text or not text.strip():
37
+ return {}, "⚠️ Please type something first!"
38
+ if model is None:
39
+ return {}, "⚠️ Model files missing in this folder."
40
+
41
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
42
+ model.eval()
43
+ with torch.no_grad():
44
+ outputs = model(**inputs)
45
+ probs = torch.sigmoid(outputs.logits).numpy()[0]
46
+
47
+ results = {}
48
+ detected_emotions = []
49
+
50
+ for i, label in enumerate(LABELS):
51
+ score = float(probs[i])
52
+ results[label] = score
53
+ if score > THRESHOLDS.get(label, 0.5):
54
+ detected_emotions.append(label.upper())
55
+
56
+ if not detected_emotions:
57
+ final_verdict = "😐 No strong emotion detected."
58
+ else:
59
+ final_verdict = " ".join([f"**{e}**" for e in detected_emotions])
60
+
61
+ return results, final_verdict
62
+
63
+ # --- 4. PROFESSIONAL CSS (The "Form" Look) ---
64
+ custom_css = """
65
+ /* 1. Background Gradient */
66
+ .gradio-container {
67
+ background: linear-gradient(135deg, #e0e7ff 0%, #f3f4f6 100%) !important;
68
+ }
69
+
70
+ /* 2. The White Card Container */
71
+ .form-card {
72
+ max-width:600px;
73
+ margin:auto;
74
+ background: white !important;
75
+ border-radius: 12px !important;
76
+ padding: 30px !important;
77
+ box-shadow: 0 10px 30px rgba(0,0,0,0.1) !important;
78
+ border-top: 6px solid #6366f1 !important; /* Indigo Top Bar */
79
+ border: 1px solid #e5e7eb !important;
80
+ }
81
+
82
+ /* 3. Header Text */
83
+ .form-header h1 {
84
+ color: #4338ca;
85
+ text-align: center;
86
+ font-weight: 800;
87
+ margin-bottom: 5px;
88
+ }
89
+ .form-header p {
90
+ color: #6b7280;
91
+ text-align: center;
92
+ margin-bottom: 20px;
93
+ }
94
+
95
+ /* 4. Button Styling */
96
+ button.primary {
97
+ background: #4f46e5 !important;
98
+ font-size: 1.1em !important;
99
+ }
100
+ """
101
+
102
+ # --- 5. UI LAYOUT ---
103
+ theme = gr.themes.Base(primary_hue="indigo", font=[gr.themes.GoogleFont("Inter"), "system-ui"])
104
+
105
+ with gr.Blocks( title="Sentiment Check") as app:
106
+
107
+ # We wrap everything in a Column with our custom 'form-card' class
108
+ with gr.Column(elem_classes="form-card"):
109
+
110
+ # Header
111
+ gr.HTML("""
112
+ <div class="form-header">
113
+ <h1>🧠 Sentiment Check</h1>
114
+ <p>Advanced Neural Emotion Detection System</p>
115
+ </div>
116
+ """)
117
+
118
+ # Section 1: Input
119
+ gr.Markdown("### 1. Source Text")
120
+ txt_input = gr.Textbox(
121
+ lines=4,
122
+ placeholder="Type your text here...",
123
+ show_label=False,
124
+ container=False # Makes it look cleaner
125
+ )
126
+
127
+ # Action Button
128
+ btn_run = gr.Button("GENERATE REPORT", variant="primary", size="lg")
129
+
130
+ # Divider
131
+ gr.HTML("<hr style='margin: 20px 0; border: 0; border-top: 1px solid #e5e7eb;'>")
132
+
133
+ # Section 2: Results
134
+ gr.Markdown("### 2. Analysis Results")
135
+ with gr.Row():
136
+ with gr.Column(scale=1):
137
+ lbl_verdict = gr.Markdown("**Status:** Waiting for data...", label="Prediction")
138
+ with gr.Column(scale=1):
139
+ lbl_chart = gr.Label(num_top_classes=5, label="Confidence Spectrum")
140
+
141
+ # Footer
142
+ gr.Markdown(
143
+ "<div style='text-align:center; color:#9ca3af; margin-top:15px; font-size:0.8em;'>Secure Local Deployment • Powered by RoBERTa</div>"
144
+ )
145
+
146
+ # Logic
147
+ btn_run.click(fn=analyze, inputs=txt_input, outputs=[lbl_chart, lbl_verdict])
148
+
 
149
  app.launch(theme=theme, css=custom_css,share=False)#,auth=("admin", "pass123"))