MatteoFasulo commited on
Commit
00e7065
·
verified ·
1 Parent(s): 81f255c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +113 -0
app.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import spaces
3
+ import torch
4
+ from transformers import pipeline
5
+
6
+ # Initialize the model
7
+ @spaces.GPU
8
+ def load_model():
9
+ return pipeline(
10
+ "text-classification",
11
+ model="MatteoFasulo/xlm-roberta-xstance",
12
+ device=0 # Use GPU
13
+ )
14
+
15
+ # Load model at startup
16
+ classifier = load_model()
17
+
18
+ # Prediction function
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
+ # Get prediction
25
+ result = classifier({"text": question, "text_pair": comment})
26
+ label = result[0]['label']
27
+ score = result[0]['score']
28
+
29
+ # Format the output
30
+ if label == "FAVOR":
31
+ emoji = "✅"
32
+ color = "green"
33
+ explanation = "The comment **supports** the political question."
34
+ else:
35
+ emoji = "❌"
36
+ color = "red"
37
+ explanation = "The comment **opposes** the political question."
38
+
39
+ # Create formatted output
40
+ output = f"""
41
+ ### {emoji} Prediction: **{label}**
42
+
43
+ <div style="padding: 10px; border-left: 4px solid {color}; background-color: #f5f5f5; margin: 10px 0;">
44
+ {explanation}
45
+ </div>
46
+
47
+ **Confidence:** {score:.2%}
48
+
49
+ ---
50
+ *💡 Tip: Try questions in German, French, Italian, or English!*
51
+ """
52
+
53
+ return output, {"FAVOR": score if label == "FAVOR" else 1-score,
54
+ "AGAINST": score if label == "AGAINST" else 1-score}
55
+
56
+ # Create Gradio interface
57
+ with gr.Blocks(title="Multilingual Stance Detection", theme=gr.themes.Soft()) as demo:
58
+ gr.Markdown("""
59
+ # 🌍 Multilingual Political Stance Detection
60
+
61
+ This model predicts whether a comment **supports (FAVOR)** or **opposes (AGAINST)** a given political question.
62
+ It works across multiple languages: 🇩🇪 German, 🇫🇷 French, 🇮🇹 Italian, and 🇬🇧 English.
63
+ """)
64
+
65
+ with gr.Row():
66
+ with gr.Column():
67
+ question_input = gr.Textbox(
68
+ label="🗳️ Political Question",
69
+ placeholder="e.g., Should Switzerland ban nuclear power plants?",
70
+ lines=3
71
+ )
72
+ comment_input = gr.Textbox(
73
+ label="💬 Comment",
74
+ placeholder="e.g., Renewable energy should replace nuclear power because it is safer and more sustainable.",
75
+ lines=5
76
+ )
77
+ submit_btn = gr.Button("🔍 Analyze Stance", variant="primary")
78
+
79
+ with gr.Column():
80
+ output_text = gr.Markdown(label="Analysis Results")
81
+ confidence_plot = gr.Label(
82
+ label="Confidence Distribution",
83
+ num_top_classes=2
84
+ )
85
+
86
+ # Example inputs
87
+ gr.Examples(
88
+ examples=[
89
+ ["Should Switzerland ban nuclear power plants?",
90
+ "Renewable energy should replace nuclear power because it is safer and more sustainable."],
91
+ ["Should Switzerland join the European Union?",
92
+ "Switzerland must maintain its independence and neutrality at all costs."],
93
+ ["Sollte die Schweiz erneuerbare Energien stärker fördern?",
94
+ "Investitionen in erneuerbare Energien reduzieren Emissionen und verbessern die Energieunabhängigkeit."],
95
+ ["La Suisse devrait-elle augmenter les subventions pour les transports publics?",
96
+ "De meilleurs transports publics profitent à tous les citoyens et réduisent le trafic."],
97
+ ["La Svizzera dovrebbe eliminare gradualmente l'energia nucleare?",
98
+ "L'energia nucleare è pericolosa e dovrebbe essere sostituita con alternative più sicure."],
99
+ ],
100
+ inputs=[question_input, comment_input],
101
+ label="📝 Try these examples"
102
+ )
103
+
104
+ # Handle submission
105
+ submit_btn.click(
106
+ fn=predict_stance,
107
+ inputs=[question_input, comment_input],
108
+ outputs=[output_text, confidence_plot]
109
+ )
110
+
111
+ # Launch the app
112
+ if __name__ == "__main__":
113
+ demo.launch()