armaniii commited on
Commit
d475e06
Β·
verified Β·
1 Parent(s): 7b2a389

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -37
app.py CHANGED
@@ -114,7 +114,7 @@ def classify_sentence(sentence, progress=gr.Progress()):
114
 
115
  if not sentence or sentence.strip() == "":
116
  status_msg = "⚠️ Please enter a sentence to classify."
117
- yield status_msg, status_msg
118
  return # End generator
119
 
120
  try:
@@ -122,7 +122,7 @@ def classify_sentence(sentence, progress=gr.Progress()):
122
  progress(0.1, desc="πŸ”¨ Building prompt...")
123
  print("Step 1: Building prompt...")
124
  status_1 = "⏳ **Step 1/4:** Building prompt..."
125
- yield status_1, status_1
126
 
127
  conversation = [
128
  {"role": "system", "content": SYSTEM_PROMPT},
@@ -132,7 +132,8 @@ def classify_sentence(sentence, progress=gr.Progress()):
132
  prompt = tokenizer.apply_chat_template(
133
  conversation=conversation,
134
  tokenize=False,
135
- add_generation_prompt=True
 
136
  )
137
  print(f"Prompt length: {len(prompt)} chars")
138
 
@@ -140,7 +141,7 @@ def classify_sentence(sentence, progress=gr.Progress()):
140
  progress(0.3, desc="πŸ€– Running model inference...")
141
  print("Step 2: Running model inference...")
142
  status_2 = "⏳ **Step 2/4:** Running model inference... (this may take 10-30 seconds)"
143
- yield status_2, status_2
144
 
145
  responses = text_pipeline(
146
  prompt,
@@ -156,7 +157,7 @@ def classify_sentence(sentence, progress=gr.Progress()):
156
  progress(0.8, desc="βš™οΈ Processing results...")
157
  print("Step 3: Processing results...")
158
  status_3 = "⏳ **Step 3/4:** Processing results..."
159
- yield status_3, status_3
160
 
161
  response_text = RESPONSE_START + responses[0]['generated_text']
162
  print(f"Response: {response_text[:200]}...")
@@ -173,53 +174,67 @@ def classify_sentence(sentence, progress=gr.Progress()):
173
 
174
  # Determine background color based on label
175
  color_map = {
176
- 'a': {'bg': '#e3f2fd', 'text': '#1976d2', 'border': '#1976d2'},
177
- 'b': {'bg': '#fff9c4', 'text': '#f57f17', 'border': '#f57f17'},
178
- 'c': {'bg': '#e8f5e9', 'text': '#388e3c', 'border': '#388e3c'},
179
- 'd': {'bg': '#ffebee', 'text': '#d32f2f', 'border': '#d32f2f'}
180
  }
181
  colors = color_map.get(label, color_map['a'])
182
 
183
- classification_output = f"""
184
- <div style="border: 1px solid #e0e0e0; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.1); margin: 20px 0;">
185
- <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px; text-align: center;">
186
- <h3 style="margin: 0; font-size: 1.2em;">Classification Result</h3>
 
187
  </div>
188
- <div style="background-color: {colors['bg']}; color: {colors['text']}; padding: 30px 20px; text-align: center; border-left: 6px solid {colors['border']};">
189
- <h2 style="margin: 0; font-size: 2em; font-weight: bold;">{label_name}</h2>
 
 
 
190
  </div>
191
- <div style="background-color: #f8f9fa; padding: 20px; border-top: 2px solid #e0e0e0;">
192
- <p style="margin: 0; font-size: 1.1em;"><strong>Category:</strong> {label_desc}</p>
193
- </div>
194
- <div style="background-color: white; padding: 20px; border-top: 2px solid #e0e0e0;">
195
- <p style="margin: 0; line-height: 1.6;"><strong>Model Explanation:</strong></p>
196
- <p style="margin: 10px 0 0 0; line-height: 1.6;">{response_text}</p>
197
  </div>
198
  </div>
 
 
 
 
 
 
 
 
 
 
 
199
  """
200
 
201
  progress(1.0, desc="βœ… Complete!")
202
  print(f"Classification complete! Label: {label_name}")
203
  print(f"{'='*80}\n")
204
 
205
- # Final result with success status - YIELD instead of return
206
  final_status = f"βœ… **Classification Complete!** Result: {label_name}"
207
- yield final_status, classification_output
208
 
209
  except Exception as e:
210
- error_message = f"""
211
- <div style="border: 1px solid #f44336; border-radius: 12px; padding: 20px; background-color: #ffebee; margin: 20px 0;">
212
- <h3 style="color: #d32f2f; margin-top: 0;">⚠️ Error</h3>
213
- <p>An error occurred during classification. Please try again.</p>
214
- <p><strong>Error details:</strong> {str(e)}</p>
215
- <p style="margin-bottom: 0;">If the problem persists, please check the model configuration.</p>
216
  </div>
217
  """
218
  print(f"Error in classify_sentence: {e}")
219
  import traceback
220
  traceback.print_exc()
221
  error_status = f"❌ **Error:** {str(e)}"
222
- yield error_status, error_message
 
223
 
224
 
225
  # ============================================================================
@@ -309,18 +324,24 @@ with gr.Blocks(css=custom_css, title="Populism Detector") as demo:
309
  elem_id="status_box"
310
  )
311
 
312
- # Results output
313
- output_text = gr.Markdown(
314
  value="",
315
- label="Analysis Result",
316
- elem_id="output_box"
317
  )
318
 
 
 
 
 
 
 
 
319
  gr.Markdown("### πŸ“ Try these examples:")
320
  gr.Examples(
321
  examples=examples,
322
  inputs=input_text,
323
- outputs=[status_box, output_text],
324
  fn=classify_sentence,
325
  cache_examples=False
326
  )
@@ -329,7 +350,7 @@ with gr.Blocks(css=custom_css, title="Populism Detector") as demo:
329
  submit_btn.click(
330
  fn=classify_sentence,
331
  inputs=input_text,
332
- outputs=[status_box, output_text],
333
  api_name="classify",
334
  show_progress="full" # Show full progress bar with percentage
335
  )
@@ -338,7 +359,7 @@ with gr.Blocks(css=custom_css, title="Populism Detector") as demo:
338
  input_text.submit(
339
  fn=classify_sentence,
340
  inputs=input_text,
341
- outputs=[status_box, output_text],
342
  show_progress="full"
343
  )
344
 
 
114
 
115
  if not sentence or sentence.strip() == "":
116
  status_msg = "⚠️ Please enter a sentence to classify."
117
+ yield status_msg, "", ""
118
  return # End generator
119
 
120
  try:
 
122
  progress(0.1, desc="πŸ”¨ Building prompt...")
123
  print("Step 1: Building prompt...")
124
  status_1 = "⏳ **Step 1/4:** Building prompt..."
125
+ yield status_1, "", ""
126
 
127
  conversation = [
128
  {"role": "system", "content": SYSTEM_PROMPT},
 
132
  prompt = tokenizer.apply_chat_template(
133
  conversation=conversation,
134
  tokenize=False,
135
+ add_generation_prompt=True,
136
+ enable_thinking=False # Disable thinking to match audit_llms.py behavior
137
  )
138
  print(f"Prompt length: {len(prompt)} chars")
139
 
 
141
  progress(0.3, desc="πŸ€– Running model inference...")
142
  print("Step 2: Running model inference...")
143
  status_2 = "⏳ **Step 2/4:** Running model inference... (this may take 10-30 seconds)"
144
+ yield status_2, "", ""
145
 
146
  responses = text_pipeline(
147
  prompt,
 
157
  progress(0.8, desc="βš™οΈ Processing results...")
158
  print("Step 3: Processing results...")
159
  status_3 = "⏳ **Step 3/4:** Processing results..."
160
+ yield status_3, "", ""
161
 
162
  response_text = RESPONSE_START + responses[0]['generated_text']
163
  print(f"Response: {response_text[:200]}...")
 
174
 
175
  # Determine background color based on label
176
  color_map = {
177
+ 'a': {'bg': '#e3f2fd', 'text': '#0d47a1', 'border': '#1976d2', 'name': 'No Populism'},
178
+ 'b': {'bg': '#fff9c4', 'text': '#e65100', 'border': '#f57f17', 'name': 'Anti-Elitism'},
179
+ 'c': {'bg': '#e8f5e9', 'text': '#1b5e20', 'border': '#388e3c', 'name': 'People-Centrism'},
180
+ 'd': {'bg': '#ffebee', 'text': '#b71c1c', 'border': '#d32f2f', 'name': 'Both'}
181
  }
182
  colors = color_map.get(label, color_map['a'])
183
 
184
+ # Result card HTML with DARK text on light backgrounds
185
+ result_html = f"""
186
+ <div style="border: 2px solid {colors['border']}; border-radius: 16px; overflow: hidden; box-shadow: 0 8px 16px rgba(0,0,0,0.15); margin: 20px 0; background-color: white;">
187
+ <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; text-align: center;">
188
+ <h2 style="margin: 0; font-size: 1.4em; font-weight: 600;">🎯 Classification Result</h2>
189
  </div>
190
+ <div style="background-color: {colors['bg']}; padding: 40px 30px; text-align: center; border-left: 8px solid {colors['border']};">
191
+ <div style="font-size: 3em; margin-bottom: 10px;">{label_name.split()[0]}</div>
192
+ <h1 style="margin: 0; font-size: 2.2em; font-weight: bold; color: {colors['text']}; line-height: 1.3;">
193
+ {colors['name']}
194
+ </h1>
195
  </div>
196
+ <div style="background-color: #f8f9fa; padding: 25px 30px; border-top: 2px solid #e0e0e0;">
197
+ <p style="margin: 0; font-size: 1.15em; color: #333; line-height: 1.6;">
198
+ <strong style="color: #000;">Description:</strong> {label_desc}
199
+ </p>
 
 
200
  </div>
201
  </div>
202
+ """
203
+
204
+ # Reasoning markdown with VISIBLE text
205
+ reasoning_md = f"""
206
+ ### Model's Detailed Reasoning
207
+
208
+ {response_text}
209
+
210
+ ---
211
+
212
+ **Note:** This is the model's explanation for its classification decision. The reasoning shows how the model analyzed the sentence based on the populism detection criteria.
213
  """
214
 
215
  progress(1.0, desc="βœ… Complete!")
216
  print(f"Classification complete! Label: {label_name}")
217
  print(f"{'='*80}\n")
218
 
219
+ # Final result with success status - YIELD 3 outputs
220
  final_status = f"βœ… **Classification Complete!** Result: {label_name}"
221
+ yield final_status, result_html, reasoning_md
222
 
223
  except Exception as e:
224
+ error_html = f"""
225
+ <div style="border: 2px solid #f44336; border-radius: 12px; padding: 25px; background-color: #ffebee; margin: 20px 0;">
226
+ <h3 style="color: #b71c1c; margin-top: 0; font-size: 1.5em;">⚠️ Error</h3>
227
+ <p style="color: #333; font-size: 1.1em; line-height: 1.6;">An error occurred during classification. Please try again.</p>
228
+ <p style="color: #333;"><strong style="color: #000;">Error details:</strong> {str(e)}</p>
229
+ <p style="margin-bottom: 0; color: #666;">If the problem persists, please check the model configuration.</p>
230
  </div>
231
  """
232
  print(f"Error in classify_sentence: {e}")
233
  import traceback
234
  traceback.print_exc()
235
  error_status = f"❌ **Error:** {str(e)}"
236
+ error_reasoning = "No reasoning available due to error."
237
+ yield error_status, error_html, error_reasoning
238
 
239
 
240
  # ============================================================================
 
324
  elem_id="status_box"
325
  )
326
 
327
+ # Classification result card (always visible)
328
+ result_card = gr.HTML(
329
  value="",
330
+ label="Classification Result"
 
331
  )
332
 
333
+ # Model reasoning (collapsible)
334
+ with gr.Accordion("πŸ“– Show Model Reasoning", open=False) as reasoning_accordion:
335
+ reasoning_text = gr.Markdown(
336
+ value="",
337
+ label=""
338
+ )
339
+
340
  gr.Markdown("### πŸ“ Try these examples:")
341
  gr.Examples(
342
  examples=examples,
343
  inputs=input_text,
344
+ outputs=[status_box, result_card, reasoning_text],
345
  fn=classify_sentence,
346
  cache_examples=False
347
  )
 
350
  submit_btn.click(
351
  fn=classify_sentence,
352
  inputs=input_text,
353
+ outputs=[status_box, result_card, reasoning_text],
354
  api_name="classify",
355
  show_progress="full" # Show full progress bar with percentage
356
  )
 
359
  input_text.submit(
360
  fn=classify_sentence,
361
  inputs=input_text,
362
+ outputs=[status_box, result_card, reasoning_text],
363
  show_progress="full"
364
  )
365