Spaces:
Build error
Build error
File size: 9,616 Bytes
02b59bf abb7957 0730894 02b59bf abb7957 0730894 abb7957 02b59bf abb7957 d4622cb abb7957 d4622cb abb7957 d4622cb abb7957 d4622cb abb7957 d4622cb abb7957 d4622cb abb7957 d4622cb abb7957 d4622cb abb7957 d4622cb abb7957 d4622cb abb7957 d4622cb abb7957 cbdbf75 6c9e71a abb7957 cbdbf75 abb7957 d4622cb abb7957 d4622cb abb7957 | 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 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 | import gradio as gr
import torch
from transformers import RobertaTokenizer, RobertaForSequenceClassification
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import json
import numpy as np
from functools import lru_cache
# Cache the model loading
@lru_cache(maxsize=1)
def load_model():
model_path = "MMADS/MoralFoundationsClassifier"
model = RobertaForSequenceClassification.from_pretrained(model_path)
tokenizer = RobertaTokenizer.from_pretrained(model_path)
# Load label names
label_names = [
"care_virtue", "care_vice",
"fairness_virtue", "fairness_vice",
"loyalty_virtue", "loyalty_vice",
"authority_virtue", "authority_vice",
"sanctity_virtue", "sanctity_vice"
]
return model, tokenizer, label_names
def predict_batch(texts, model, tokenizer, label_names):
"""Process texts in batch for efficiency"""
# Tokenize all texts at once
inputs = tokenizer(texts, padding=True, truncation=True, max_length=512, return_tensors="pt")
# Get predictions
with torch.no_grad():
outputs = model(**inputs)
predictions = torch.sigmoid(outputs.logits)
# Convert to numpy array
predictions = predictions.numpy()
# Create results for each text
results = []
for i, text in enumerate(texts):
scores = {label: float(predictions[i, j]) for j, label in enumerate(label_names)}
results.append({
'text': text,
'scores': scores
})
return results
def create_visualization(results):
"""Create visualization for moral foundation scores"""
if not results:
return None
# Aggregate scores across all texts
all_scores = {}
for label in results[0]['scores'].keys():
all_scores[label] = [r['scores'][label] for r in results]
# Create grouped bar chart
foundations = ['care', 'fairness', 'loyalty', 'authority', 'sanctity']
virtues = []
vices = []
for foundation in foundations:
virtue_scores = all_scores[f"{foundation}_virtue"]
vice_scores = all_scores[f"{foundation}_vice"]
virtues.append(np.mean(virtue_scores))
vices.append(np.mean(vice_scores))
fig = go.Figure()
fig.add_trace(go.Bar(
name='Virtues',
x=foundations,
y=virtues,
marker_color='lightgreen'
))
fig.add_trace(go.Bar(
name='Vices',
x=foundations,
y=vices,
marker_color='lightcoral'
))
fig.update_layout(
title="Average Moral Foundation Scores",
xaxis_title="Moral Foundations",
yaxis_title="Average Score",
barmode='group',
yaxis=dict(range=[0, 1]),
template="plotly_white"
)
return fig
def create_heatmap(results):
"""Create heatmap visualization"""
if not results:
return None
# Create matrix for heatmap
texts = [r['text'][:50] + "..." if len(r['text']) > 50 else r['text'] for r in results]
labels = list(results[0]['scores'].keys())
matrix = []
for result in results:
matrix.append([result['scores'][label] for label in labels])
fig = px.imshow(
matrix,
labels=dict(x="Moral Foundations", y="Texts", color="Score"),
x=labels,
y=texts,
aspect="auto",
color_continuous_scale="RdBu_r"
)
fig.update_layout(
title="Moral Foundation Scores Heatmap",
height=max(400, len(texts) * 30)
)
return fig
def process_text(text):
"""Process single text input"""
model, tokenizer, label_names = load_model()
results = predict_batch([text], model, tokenizer, label_names)
# Format output
scores_text = "**Moral Foundation Scores:**\n\n"
for label, score in results[0]['scores'].items():
foundation = label.replace('_', ' ').title()
scores_text += f"{foundation}: {score:.4f}\n"
# Create visualizations
bar_chart = create_visualization(results)
return scores_text, bar_chart
def process_csv(file, progress=gr.Progress()):
"""Process CSV file with multiple texts"""
if file is None:
return "Please upload a CSV file", None, None, None
try:
# Read CSV
df = pd.read_csv(file.name)
if 'text' not in df.columns:
return "Error: CSV must contain a 'text' column", None, None, None
texts = df['text'].tolist()
# Load model and process in batches
progress(0, desc="Loading model...")
model, tokenizer, label_names = load_model()
# Process in batches of 32
batch_size = 32
all_results = []
total_batches = (len(texts) + batch_size - 1) // batch_size
for i in range(0, len(texts), batch_size):
batch_num = i // batch_size + 1
progress(batch_num / total_batches, desc=f"Processing batch {batch_num}/{total_batches}")
batch_texts = texts[i:i+batch_size]
batch_results = predict_batch(batch_texts, model, tokenizer, label_names)
all_results.extend(batch_results)
progress(0.9, desc="Creating visualizations...")
# Create summary
summary = f"**Processed {len(texts)} texts**\n\n"
summary += "**Average Scores Across All Texts:**\n\n"
# Calculate average scores
avg_scores = {}
for label in label_names:
avg_scores[label] = np.mean([r['scores'][label] for r in all_results])
summary += f"{label.replace('_', ' ').title()}: {avg_scores[label]:.4f}\n"
# Create visualizations
bar_chart = create_visualization(all_results)
heatmap = create_heatmap(all_results[:20]) # Limit heatmap to first 20 texts
# Create downloadable results
results_df = pd.DataFrame([
{
'text': r['text'],
**r['scores']
} for r in all_results
])
# Save to a temporary file and return the path
output_path = "results.csv"
results_df.to_csv(output_path, index=False)
return summary, bar_chart, heatmap, output_path
except Exception as e:
return f"Error processing CSV: {str(e)}", None, None, None
# Create example texts
example_texts = [
"We must protect the vulnerable and care for those who cannot care for themselves.",
"Everyone deserves equal treatment under the law, regardless of their background.",
"Betraying your country is one of the worst things a person can do.",
"We should respect our elders and follow traditional values.",
"Some things are sacred and should not be violated or mocked."
]
# Create Gradio interface
with gr.Blocks(title="Moral Foundations Classifier") as demo:
gr.Markdown("""
# Moral Foundations Classifier
This app analyzes text for moral foundations based on Moral Foundations Theory.
It identifies five moral foundations (each with virtue and vice dimensions):
- **Care/Harm**: Compassion and protection vs. harm
- **Fairness/Cheating**: Justice and equality vs. cheating
- **Loyalty/Betrayal**: Group loyalty vs. betrayal
- **Authority/Subversion**: Respect for authority vs. subversion
- **Sanctity/Degradation**: Purity and sanctity vs. degradation
""")
with gr.Tab("Single Text Analysis"):
text_input = gr.Textbox(
label="Enter text to analyze",
placeholder="Type or paste your text here...",
lines=5
)
gr.Examples(
examples=example_texts,
inputs=text_input,
label="Example Texts"
)
analyze_btn = gr.Button("Analyze Text", variant="primary")
with gr.Row():
scores_output = gr.Markdown(label="Scores")
chart_output = gr.Plot(label="Visualization")
analyze_btn.click(
fn=process_text,
inputs=text_input,
outputs=[scores_output, chart_output]
)
with gr.Tab("Batch Analysis (CSV)"):
gr.Markdown("""
Upload a CSV file with a 'text' column containing the texts to analyze.
The app will process all texts and provide aggregate visualizations.
A sample CSV file is available for download <a href="https://huggingface.co/spaces/MMADS/MoralFoundationsClassifier-app/tree/main/examples" target="_blank" rel="noopener noreferrer">here</a>.
""")
csv_input = gr.File(
label="Upload CSV file",
file_types=[".csv"]
)
process_btn = gr.Button("Process CSV", variant="primary")
summary_output = gr.Markdown(label="Summary")
with gr.Row():
bar_output = gr.Plot(label="Average Scores")
heatmap_output = gr.Plot(label="Scores Heatmap (First 20 texts)")
# Add download component
download_output = gr.File(label="Download Results", visible=True)
process_btn.click(
fn=process_csv,
inputs=csv_input,
outputs=[summary_output, bar_output, heatmap_output, download_output]
)
gr.Markdown("""
---
Based on the [MoralFoundationsClassifier](https://huggingface.co/MMADS/MoralFoundationsClassifier) by M. Murat Ardag
""")
if __name__ == "__main__":
demo.launch() |