MatteoFasulo commited on
Commit
b4a2a07
Β·
verified Β·
1 Parent(s): 68f66ad

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -30
app.py CHANGED
@@ -3,7 +3,6 @@ import spaces
3
  import torch
4
  from transformers import pipeline
5
 
6
- # Don't load model globally - ZeroGPU doesn't allow CUDA operations outside @spaces.GPU
7
  classifier = None
8
 
9
  def get_classifier():
@@ -13,36 +12,44 @@ def get_classifier():
13
  classifier = pipeline(
14
  "text-classification",
15
  model="MatteoFasulo/xlm-roberta-xstance",
16
- device=0 # This will work inside @spaces.GPU context
17
  )
18
  return classifier
19
 
20
- # Prediction function - all CUDA ops happen here
21
  @spaces.GPU
22
  def predict_stance(question, comment):
23
  if not question.strip() or not comment.strip():
24
  return "⚠️ Please provide both a question and a comment.", None
25
 
26
- # Get classifier (lazy loading inside GPU context)
27
- model = get_classifier()
28
-
29
- # Get prediction
30
- result = model({"text": question, "text_pair": comment})
31
- label = result[0]['label']
32
- score = result[0]['score']
33
-
34
- # Format the output
35
- if label == "FAVOR":
36
- emoji = "βœ…"
37
- color = "green"
38
- explanation = "The comment **supports** the political question."
39
- else:
40
- emoji = "❌"
41
- color = "red"
42
- explanation = "The comment **opposes** the political question."
43
-
44
- # Create formatted output
45
- output = f"""
 
 
 
 
 
 
 
 
 
46
  ### {emoji} Prediction: **{label}**
47
 
48
  <div style="padding: 10px; border-left: 4px solid {color}; background-color: #f5f5f5; margin: 10px 0;">
@@ -53,12 +60,21 @@ def predict_stance(question, comment):
53
 
54
  ---
55
  *πŸ’‘ Tip: Try questions in German, French, Italian, or English!*
56
- """
57
-
58
- return output, {"FAVOR": score if label == "FAVOR" else 1-score,
59
- "AGAINST": score if label == "AGAINST" else 1-score}
 
 
 
 
 
 
 
 
 
 
60
 
61
- # Create Gradio interface
62
  with gr.Blocks(title="Multilingual Stance Detection", theme=gr.themes.Soft()) as demo:
63
  gr.Markdown("""
64
  # 🌍 Multilingual Political Stance Detection
@@ -106,13 +122,17 @@ with gr.Blocks(title="Multilingual Stance Detection", theme=gr.themes.Soft()) as
106
  label="πŸ“ Try these examples"
107
  )
108
 
109
- # Handle submission
110
  submit_btn.click(
111
  fn=predict_stance,
112
  inputs=[question_input, comment_input],
113
  outputs=[output_text, confidence_plot]
114
  )
 
 
 
 
 
 
115
 
116
- # Launch the app
117
  if __name__ == "__main__":
118
  demo.launch()
 
3
  import torch
4
  from transformers import pipeline
5
 
 
6
  classifier = None
7
 
8
  def get_classifier():
 
12
  classifier = pipeline(
13
  "text-classification",
14
  model="MatteoFasulo/xlm-roberta-xstance",
15
+ device=0
16
  )
17
  return classifier
18
 
 
19
  @spaces.GPU
20
  def predict_stance(question, comment):
21
  if not question.strip() or not comment.strip():
22
  return "⚠️ Please provide both a question and a comment.", None
23
 
24
+ try:
25
+ # Get classifier
26
+ model = get_classifier()
27
+
28
+ # Get prediction
29
+ result = model({"text": question, "text_pair": comment})
30
+
31
+ if isinstance(result, list) and len(result) > 0:
32
+ prediction = result[0]
33
+ label = prediction['label']
34
+ score = prediction['score']
35
+ elif isinstance(result, dict):
36
+ label = result.get('label', 'Unknown')
37
+ score = result.get('score', 0.0)
38
+ else:
39
+ return "⚠️ Unexpected model output format.", None
40
+
41
+ # Format the output
42
+ if "FAVOR" in label.upper():
43
+ emoji = "βœ…"
44
+ color = "green"
45
+ explanation = "The comment **supports** the political question."
46
+ else:
47
+ emoji = "❌"
48
+ color = "red"
49
+ explanation = "The comment **opposes** the political question."
50
+
51
+ # Create formatted output
52
+ output = f"""
53
  ### {emoji} Prediction: **{label}**
54
 
55
  <div style="padding: 10px; border-left: 4px solid {color}; background-color: #f5f5f5; margin: 10px 0;">
 
60
 
61
  ---
62
  *πŸ’‘ Tip: Try questions in German, French, Italian, or English!*
63
+ """
64
+
65
+ # Calculate confidence distribution
66
+ if "FAVOR" in label.upper():
67
+ confidence_dist = {"FAVOR": score, "AGAINST": 1 - score}
68
+ else:
69
+ confidence_dist = {"AGAINST": score, "FAVOR": 1 - score}
70
+
71
+ return output, confidence_dist
72
+
73
+ except Exception as e:
74
+ error_msg = f"❌ Error during prediction: {str(e)}"
75
+ print(f"Detailed error: {e}")
76
+ return error_msg, None
77
 
 
78
  with gr.Blocks(title="Multilingual Stance Detection", theme=gr.themes.Soft()) as demo:
79
  gr.Markdown("""
80
  # 🌍 Multilingual Political Stance Detection
 
122
  label="πŸ“ Try these examples"
123
  )
124
 
 
125
  submit_btn.click(
126
  fn=predict_stance,
127
  inputs=[question_input, comment_input],
128
  outputs=[output_text, confidence_plot]
129
  )
130
+
131
+ comment_input.submit(
132
+ fn=predict_stance,
133
+ inputs=[question_input, comment_input],
134
+ outputs=[output_text, confidence_plot]
135
+ )
136
 
 
137
  if __name__ == "__main__":
138
  demo.launch()