Spaces:
Running on Zero
Running on Zero
File size: 8,255 Bytes
00e7065 406c826 00e7065 406c826 68f66ad 406c826 00e7065 406c826 00e7065 406c826 b4a2a07 406c826 b4a2a07 406c826 b4a2a07 406c826 b4a2a07 406c826 b4a2a07 406c826 b4a2a07 406c826 b4a2a07 00e7065 406c826 00e7065 406c826 00e7065 dcb29d4 b4a2a07 406c826 b4a2a07 406c826 b4a2a07 406c826 b4a2a07 00e7065 406c826 00e7065 406c826 00e7065 406c826 00e7065 406c826 00e7065 dcb29d4 406c826 00e7065 406c826 00e7065 dcb29d4 406c826 00e7065 406c826 00e7065 406c826 00e7065 406c826 00e7065 406c826 00e7065 406c826 00e7065 406c826 00e7065 406c826 00e7065 406c826 00e7065 406c826 b4a2a07 406c826 b4a2a07 00e7065 406c826 00e7065 | 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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | import gradio as gr
import spaces
from transformers import pipeline
# Available models shown in the dropdown.
MODEL_OPTIONS = {
"XLM-RoBERTa X-Stance": "MatteoFasulo/xlm-roberta-xstance",
"mDeBERTa-v3 X-Stance": "MatteoFasulo/mdeberta-v3-xstance",
}
# Cache one classifier for each model so it is not reloaded on every request.
classifiers = {}
def get_classifier(model_name):
if model_name not in classifiers:
classifiers[model_name] = pipeline(
task="text-classification",
model=model_name,
device=0,
)
return classifiers[model_name]
@spaces.GPU
def predict_stance(selected_model, question, comment):
if not question.strip() or not comment.strip():
return "⚠️ Please provide both a question and a comment.", None
try:
model_name = MODEL_OPTIONS[selected_model]
model = get_classifier(model_name)
result = model(
{
"text": question,
"text_pair": comment,
}
)
if isinstance(result, list) and len(result) > 0:
prediction = result[0]
label = prediction["label"]
score = prediction["score"]
elif isinstance(result, dict):
label = result.get("label", "Unknown")
score = result.get("score", 0.0)
else:
return "⚠️ Unexpected model output format.", None
normalized_label = label.upper()
if "FAVOR" in normalized_label:
emoji = "✅"
color = "green"
explanation = "The comment **supports** the political question."
elif "AGAINST" in normalized_label:
emoji = "❌"
color = "red"
explanation = "The comment **opposes** the political question."
else:
emoji = "❓"
color = "orange"
explanation = "The model returned an unrecognized stance label."
output = f"""
### {emoji} Prediction: **{label}**
<div style="
padding: 10px;
border-left: 4px solid {color};
background-color: #f5f5f5;
margin: 10px 0;
">
{explanation}
</div>
**Confidence:** {score:.2%}
**Model:** `{model_name}`
---
*💡 Tip: Try questions in German or French!*
"""
if "FAVOR" in normalized_label:
confidence_dist = {
"FAVOR": score,
"AGAINST": 1 - score,
}
elif "AGAINST" in normalized_label:
confidence_dist = {
"AGAINST": score,
"FAVOR": 1 - score,
}
else:
confidence_dist = {label: score}
return output, confidence_dist
except Exception as e:
error_msg = f"❌ Error during prediction: {str(e)}"
return error_msg, None
with gr.Blocks(
title="Multilingual Stance Detection",
theme=gr.themes.Soft(),
) as demo:
gr.Markdown("""
# 🌍 Multilingual Political Stance Detection
Select a model and predict whether a comment **supports (FAVOR)**
or **opposes (AGAINST)** a political question.
The models support multilingual stance detection, including
🇩🇪 German and 🇫🇷 French.
""")
with gr.Row():
with gr.Column():
model_dropdown = gr.Dropdown(
choices=list(MODEL_OPTIONS.keys()),
value="XLM-RoBERTa X-Stance",
label="🤖 Model",
info="Choose the model used for stance classification.",
interactive=True,
)
question_input = gr.Textbox(
label="🗳️ Political Question",
lines=3,
placeholder=(
"e.g. Sollte die Schweiz die Kernenergie verbieten?"
),
)
comment_input = gr.Textbox(
label="💬 Comment",
lines=5,
placeholder=(
"e.g. Erneuerbare Energien sollten Kernenergie "
"ersetzen, weil sie sicherer und nachhaltiger sind."
),
)
submit_btn = gr.Button(
"🔍 Analyze Stance",
variant="primary",
)
with gr.Column():
output_text = gr.Markdown(
label="Analysis Results",
)
confidence_plot = gr.Label(
label="Confidence Distribution",
num_top_classes=2,
)
gr.Examples(
examples=[
[
"Sollte die Schweiz erneuerbare Energien stärker fördern?",
(
"Investitionen in erneuerbare Energien reduzieren "
"Emissionen und verbessern die Energieunabhängigkeit."
),
],
[
"Sollte die Schweiz der Europäischen Union beitreten?",
(
"Die Schweiz muss ihre Unabhängigkeit und Neutralität "
"um jeden Preis bewahren."
),
],
[
"Sollte die Schweiz die Kernenergie schrittweise abschaffen?",
(
"Kernenergie ist gefährlich und sollte durch sicherere "
"Alternativen ersetzt werden."
),
],
[
"Sollte die Schweiz die Einwanderung begrenzen?",
(
"Eine Begrenzung der Einwanderung schadet der Wirtschaft "
"und dem kulturellen Austausch."
),
],
[
(
"Sollte die Schweiz ein bedingungsloses "
"Grundeinkommen einführen?"
),
(
"Ein bedingungsloses Grundeinkommen würde die soziale "
"Sicherheit stärken und Armut reduzieren."
),
],
[
(
"La Suisse devrait-elle promouvoir davantage "
"les énergies renouvelables?"
),
(
"Les investissements dans les énergies renouvelables "
"réduisent les émissions et améliorent "
"l'indépendance énergétique."
),
],
[
"La Suisse devrait-elle adhérer à l'Union européenne?",
(
"La Suisse doit préserver son indépendance et sa "
"neutralité à tout prix."
),
],
[
(
"La Suisse devrait-elle éliminer progressivement "
"l'énergie nucléaire?"
),
(
"L'énergie nucléaire est dangereuse et devrait être "
"remplacée par des alternatives plus sûres."
),
],
[
"La Suisse devrait-elle limiter l'immigration?",
(
"La limitation de l'immigration nuit à l'économie "
"et aux échanges culturels."
),
],
[
(
"La Suisse devrait-elle introduire un revenu "
"de base inconditionnel?"
),
(
"Un revenu de base inconditionnel renforcerait la "
"sécurité sociale et réduirait la pauvreté."
),
],
],
inputs=[question_input, comment_input],
label="📝 Try these examples",
)
prediction_inputs = [
model_dropdown,
question_input,
comment_input,
]
prediction_outputs = [
output_text,
confidence_plot,
]
submit_btn.click(
fn=predict_stance,
inputs=prediction_inputs,
outputs=prediction_outputs,
)
comment_input.submit(
fn=predict_stance,
inputs=prediction_inputs,
outputs=prediction_outputs,
)
if __name__ == "__main__":
demo.launch() |