anonymous12321 commited on
Commit
9be3e52
·
verified ·
1 Parent(s): 442ebbc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -23
app.py CHANGED
@@ -1,13 +1,14 @@
1
  #!/usr/bin/env python3
2
  # -*- coding: utf-8 -*-
3
  """
4
- Gradio App - Intelligent Stacking Classifier (Dark Mode)
5
  """
6
  import gradio as gr
7
  import numpy as np
8
  import joblib
9
  import re
10
  from pathlib import Path
 
11
 
12
  # Sklearn
13
  from sklearn.feature_extraction.text import TfidfVectorizer
@@ -23,6 +24,7 @@ except ImportError:
23
  TORCH_AVAILABLE = False
24
 
25
 
 
26
  class PortugueseClassifier:
27
  def __init__(self):
28
  self.model_path = Path("models")
@@ -63,9 +65,8 @@ class PortugueseClassifier:
63
  self.bert_model = self.bert_model.to(self.device)
64
 
65
  self.models_loaded = True
66
- return f"✅ Loaded {len(self.labels)} categories"
67
  except Exception as e:
68
- return f"❌ Error loading models: {str(e)}"
69
 
70
  def extract_bert_features(self, text):
71
  if not TORCH_AVAILABLE or not self.bert_model:
@@ -81,11 +82,11 @@ class PortugueseClassifier:
81
 
82
  def predict(self, text):
83
  if not self.models_loaded:
84
- return {"error": "Models not loaded"}
85
 
86
  text = re.sub(r'\s+', ' ', text.strip())
87
  if not text:
88
- return {"error": "Empty text"}
89
 
90
  tfidf_features = self.tfidf_vectorizer.transform([text])
91
  bert_features = self.extract_bert_features(text)
@@ -134,37 +135,63 @@ class PortugueseClassifier:
134
  classifier = PortugueseClassifier()
135
 
136
 
137
- def classify_text(text):
 
 
138
  preds = classifier.predict(text)
139
- if "error" in preds:
140
- return "❌ " + preds["error"]
141
- else:
142
- results = ""
143
- for i, p in enumerate(preds[:10], 1):
144
- emoji = {"high": "🟢", "medium": "🟡", "low": "🔴"}[p["confidence"]]
145
- results += f"{i}. {p['label']} {emoji} ({p['probability']:.1%})\n"
146
- return results
147
-
148
-
149
- # Dark theme CSS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  css = """
151
- body { background-color: #121212; color: #f5f5f5; }
152
  h1, h2, h3, h4 { color: #1E90FF; }
153
  input, textarea { background-color: #1E1E1E; color: #f5f5f5; border: 1px solid #333; }
154
  button { background-color: #1E90FF; color: white; border-radius: 6px; border: none; }
155
  .gradio-container { background-color: #121212; }
156
- .output_text { background-color: #1E1E1E; color: #f5f5f5; border: 1px solid #333; padding: 10px; border-radius: 8px; }
 
157
  """
158
 
159
  with gr.Blocks(css=css, theme=None) as demo:
160
- gr.Markdown("# 🧠 Intelligent Stacking Classifier", elem_id="title")
 
161
  with gr.Row():
162
  with gr.Column():
163
- text_input = gr.Textbox(label="Enter Portuguese administrative text", lines=10, placeholder="Cole aqui o texto do documento...")
 
164
  classify_btn = gr.Button("🔍 Classify")
 
165
  with gr.Column():
166
- output = gr.Textbox(label="Predicted Categories", lines=15)
 
 
 
 
 
 
167
 
168
- classify_btn.click(classify_text, inputs=text_input, outputs=output)
169
 
170
  demo.launch()
 
1
  #!/usr/bin/env python3
2
  # -*- coding: utf-8 -*-
3
  """
4
+ Gradio App - Intelligent Stacking Classifier (Dark Mode, Cards + Loading)
5
  """
6
  import gradio as gr
7
  import numpy as np
8
  import joblib
9
  import re
10
  from pathlib import Path
11
+ from time import sleep # para simular loading (se necessário)
12
 
13
  # Sklearn
14
  from sklearn.feature_extraction.text import TfidfVectorizer
 
24
  TORCH_AVAILABLE = False
25
 
26
 
27
+ # ---------------- Modelo ----------------
28
  class PortugueseClassifier:
29
  def __init__(self):
30
  self.model_path = Path("models")
 
65
  self.bert_model = self.bert_model.to(self.device)
66
 
67
  self.models_loaded = True
 
68
  except Exception as e:
69
+ print(f"❌ Error loading models: {str(e)}")
70
 
71
  def extract_bert_features(self, text):
72
  if not TORCH_AVAILABLE or not self.bert_model:
 
82
 
83
  def predict(self, text):
84
  if not self.models_loaded:
85
+ return [{"label": "Error", "probability": 0.0, "confidence": "low"}]
86
 
87
  text = re.sub(r'\s+', ' ', text.strip())
88
  if not text:
89
+ return [{"label": "Empty text", "probability": 0.0, "confidence": "low"}]
90
 
91
  tfidf_features = self.tfidf_vectorizer.transform([text])
92
  bert_features = self.extract_bert_features(text)
 
135
  classifier = PortugueseClassifier()
136
 
137
 
138
+ def classify_text_with_loading(text):
139
+ """Simula loading, depois retorna cards"""
140
+ sleep(0.5) # delay curto para efeito visual de loading
141
  preds = classifier.predict(text)
142
+ cards = ""
143
+ for p in preds[:10]:
144
+ prob = p["probability"]
145
+ label = p["label"]
146
+ conf = p["confidence"]
147
+ color = {"high": "#28a745", "medium": "#ffc107", "low": "#dc3545"}[conf]
148
+ emoji = {"high": "🟢", "medium": "🟡", "low": "🔴"}[conf]
149
+
150
+ cards += f"""
151
+ <div style="
152
+ border-left: 6px solid {color};
153
+ background-color:#1E1E1E;
154
+ padding:12px;
155
+ margin-bottom:10px;
156
+ border-radius:8px;
157
+ transition: transform 0.2s;
158
+ ">
159
+ <strong style="color:#fff; font-size:16px;">{label}</strong> {emoji}<br>
160
+ <small style="color:#ccc">Probability: {prob:.1%}</small>
161
+ </div>
162
+ """
163
+ return cards
164
+
165
+
166
+ # CSS Dark Theme + smooth
167
  css = """
168
+ body { background-color: #121212; color: #f5f5f5; font-family: 'Segoe UI', sans-serif; }
169
  h1, h2, h3, h4 { color: #1E90FF; }
170
  input, textarea { background-color: #1E1E1E; color: #f5f5f5; border: 1px solid #333; }
171
  button { background-color: #1E90FF; color: white; border-radius: 6px; border: none; }
172
  .gradio-container { background-color: #121212; }
173
+ .output_html { background-color: #121212; color: #f5f5f5; }
174
+ .progress-bar { height: 4px; background-color:#1E90FF; width:0%; transition: width 0.5s; border-radius:2px; }
175
  """
176
 
177
  with gr.Blocks(css=css, theme=None) as demo:
178
+ gr.HTML("<h1 style='text-align:center'>🧠 Intelligent Stacking Classifier</h1>")
179
+
180
  with gr.Row():
181
  with gr.Column():
182
+ text_input = gr.Textbox(label="Enter Portuguese administrative text", lines=10,
183
+ placeholder="Cole aqui o texto do documento...")
184
  classify_btn = gr.Button("🔍 Classify")
185
+ progress = gr.HTML("<div class='progress-bar' id='loading-bar'></div>")
186
  with gr.Column():
187
+ output = gr.HTML(label="Predicted Categories")
188
+
189
+ def wrapped_click(text):
190
+ progress_bar = "<div class='progress-bar' style='width:100%'></div>"
191
+ # animação temporária
192
+ result = classify_text_with_loading(text)
193
+ return result
194
 
195
+ classify_btn.click(wrapped_click, inputs=text_input, outputs=output)
196
 
197
  demo.launch()