lisabdunlap commited on
Commit
468e203
Β·
verified Β·
1 Parent(s): 38f90e3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +337 -0
app.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ from datasets import load_dataset
4
+ import random
5
+ from typing import Dict, Any, List
6
+ import json
7
+
8
+ # Load the dataset
9
+ def load_community_alignment_dataset():
10
+ """Load the Facebook Community Alignment Dataset"""
11
+ try:
12
+ dataset = load_dataset("facebook/community-alignment-dataset")
13
+ return dataset
14
+ except Exception as e:
15
+ print(f"Error loading dataset: {e}")
16
+ return None
17
+
18
+ # Initialize dataset
19
+ dataset = load_community_alignment_dataset()
20
+
21
+ def format_conversation_turn(turn_data: Dict[str, Any], turn_number: int) -> str:
22
+ """Format a conversation turn for display"""
23
+ if not turn_data:
24
+ return ""
25
+
26
+ prompt = turn_data.get('prompt', '')
27
+ responses = turn_data.get('responses', '')
28
+ preferred = turn_data.get('preferred_response', '')
29
+
30
+ formatted = f"**Turn {turn_number}**\n\n"
31
+ formatted += f"**Prompt:** {prompt}\n\n"
32
+
33
+ if responses:
34
+ formatted += "**Responses:**\n"
35
+ formatted += responses.replace('# Response ', '**Response ').replace(':\n', ':**\n')
36
+ formatted += "\n"
37
+
38
+ if preferred:
39
+ formatted += f"**Preferred Response:** {preferred.upper()}\n"
40
+
41
+ return formatted
42
+
43
+ def get_conversation_data(conversation_id: int) -> Dict[str, Any]:
44
+ """Get conversation data by ID"""
45
+ if not dataset:
46
+ return None
47
+
48
+ # Search for conversation in the dataset
49
+ for split in dataset.keys():
50
+ for item in dataset[split]:
51
+ if item.get('conversation_id') == conversation_id:
52
+ return item
53
+ return None
54
+
55
+ def format_annotator_info(item: Dict[str, Any]) -> str:
56
+ """Format annotator information"""
57
+ info = "**Annotator Information:**\n\n"
58
+
59
+ demographics = [
60
+ ('Age', 'annotator_age'),
61
+ ('Gender', 'annotator_gender'),
62
+ ('Education', 'annotator_education_level'),
63
+ ('Political', 'annotator_political'),
64
+ ('Ethnicity', 'annotator_ethnicity'),
65
+ ('Country', 'annotator_country')
66
+ ]
67
+
68
+ for label, key in demographics:
69
+ value = item.get(key, 'N/A')
70
+ if value and value != 'None':
71
+ info += f"**{label}:** {value}\n"
72
+
73
+ return info
74
+
75
+ def display_conversation(conversation_id: int) -> tuple:
76
+ """Display a conversation by ID"""
77
+ if not dataset:
78
+ return "Dataset not loaded", "", "", ""
79
+
80
+ item = get_conversation_data(conversation_id)
81
+ if not item:
82
+ return f"Conversation ID {conversation_id} not found", "", "", ""
83
+
84
+ # Format conversation turns
85
+ conversation_text = ""
86
+
87
+ # First turn
88
+ if item.get('first_turn_prompt'):
89
+ first_turn = {
90
+ 'prompt': item['first_turn_prompt'],
91
+ 'responses': item['first_turn_responses'],
92
+ 'preferred_response': item['first_turn_preferred_response']
93
+ }
94
+ conversation_text += format_conversation_turn(first_turn, 1) + "\n"
95
+
96
+ # Second turn
97
+ if item.get('second_turn_prompt'):
98
+ second_turn = {
99
+ 'prompt': item['second_turn_prompt'],
100
+ 'responses': item['second_turn_responses'],
101
+ 'preferred_response': item['second_turn_preferred_response']
102
+ }
103
+ conversation_text += format_conversation_turn(second_turn, 2) + "\n"
104
+
105
+ # Third turn
106
+ if item.get('third_turn_prompt'):
107
+ third_turn = {
108
+ 'prompt': item['third_turn_prompt'],
109
+ 'responses': item['third_turn_responses'],
110
+ 'preferred_response': item['third_turn_preferred_response']
111
+ }
112
+ conversation_text += format_conversation_turn(third_turn, 3) + "\n"
113
+
114
+ # Fourth turn
115
+ if item.get('fourth_turn_prompt'):
116
+ fourth_turn = {
117
+ 'prompt': item['fourth_turn_prompt'],
118
+ 'responses': item['fourth_turn_responses'],
119
+ 'preferred_response': item['fourth_turn_preferred_response']
120
+ }
121
+ conversation_text += format_conversation_turn(fourth_turn, 4) + "\n"
122
+
123
+ # Annotator information
124
+ annotator_info = format_annotator_info(item)
125
+
126
+ # Metadata
127
+ metadata = f"**Metadata:**\n\n"
128
+ metadata += f"**Conversation ID:** {item.get('conversation_id', 'N/A')}\n"
129
+ metadata += f"**Language:** {item.get('assigned_lang', 'N/A')}\n"
130
+ metadata += f"**Annotator ID:** {item.get('annotator_id', 'N/A')}\n"
131
+ metadata += f"**In Balanced Subset:** {item.get('in_balanced_subset', 'N/A')}\n"
132
+ metadata += f"**In Balanced Subset 10:** {item.get('in_balanced_subset_10', 'N/A')}\n"
133
+ metadata += f"**Is Pregenerated First Prompt:** {item.get('is_pregenerated_first_prompt', 'N/A')}\n"
134
+
135
+ # Raw JSON for debugging
136
+ raw_json = json.dumps(item, indent=2)
137
+
138
+ return conversation_text, annotator_info, metadata, raw_json
139
+
140
+ def get_random_conversation() -> int:
141
+ """Get a random conversation ID"""
142
+ if not dataset:
143
+ return 0
144
+
145
+ # Get a random split and item
146
+ split = random.choice(list(dataset.keys()))
147
+ item = random.choice(dataset[split])
148
+ return item.get('conversation_id', 0)
149
+
150
+ def get_dataset_stats() -> str:
151
+ """Get dataset statistics"""
152
+ if not dataset:
153
+ return "Dataset not loaded"
154
+
155
+ stats = "**Dataset Statistics:**\n\n"
156
+
157
+ for split_name, split_data in dataset.items():
158
+ stats += f"**{split_name}:** {len(split_data)} conversations\n"
159
+
160
+ # Sample some metadata
161
+ if 'train' in dataset and len(dataset['train']) > 0:
162
+ sample_item = dataset['train'][0]
163
+ stats += f"\n**Sample Fields:**\n"
164
+ for key in list(sample_item.keys())[:10]: # Show first 10 fields
165
+ stats += f"- {key}\n"
166
+
167
+ return stats
168
+
169
+ def search_conversations(query: str, field: str) -> str:
170
+ """Search conversations by field"""
171
+ if not dataset or not query:
172
+ return "Please provide a search query"
173
+
174
+ results = []
175
+ query_lower = query.lower()
176
+
177
+ for split_name, split_data in dataset.items():
178
+ for item in split_data[:100]: # Limit search to first 100 items per split
179
+ if field in item and item[field]:
180
+ field_value = str(item[field]).lower()
181
+ if query_lower in field_value:
182
+ results.append({
183
+ 'conversation_id': item.get('conversation_id'),
184
+ 'split': split_name,
185
+ 'field_value': str(item[field])[:100] + "..." if len(str(item[field])) > 100 else str(item[field])
186
+ })
187
+
188
+ if not results:
189
+ return f"No results found for '{query}' in field '{field}'"
190
+
191
+ result_text = f"**Search Results for '{query}' in '{field}':**\n\n"
192
+ for i, result in enumerate(results[:10]): # Limit to 10 results
193
+ result_text += f"{i+1}. **Conversation ID:** {result['conversation_id']} (Split: {result['split']})\n"
194
+ result_text += f" **Value:** {result['field_value']}\n\n"
195
+
196
+ return result_text
197
+
198
+ # Create the Gradio interface
199
+ def create_interface():
200
+ with gr.Blocks(title="Facebook Community Alignment Dataset Viewer", theme=gr.themes.Soft()) as demo:
201
+ gr.Markdown("# πŸ€– Facebook Community Alignment Dataset Viewer")
202
+ gr.Markdown("Explore conversations, responses, and annotations from the Facebook Community Alignment Dataset.")
203
+
204
+ with gr.Tabs():
205
+ # Tab 1: Conversation Viewer
206
+ with gr.Tab("Conversation Viewer"):
207
+ with gr.Row():
208
+ with gr.Column(scale=1):
209
+ conversation_id_input = gr.Number(
210
+ label="Conversation ID",
211
+ value=get_random_conversation(),
212
+ interactive=True
213
+ )
214
+ random_btn = gr.Button("🎲 Random Conversation", variant="secondary")
215
+ load_btn = gr.Button("πŸ” Load Conversation", variant="primary")
216
+
217
+ with gr.Column(scale=3):
218
+ conversation_display = gr.Markdown(label="Conversation")
219
+ annotator_display = gr.Markdown(label="Annotator Information")
220
+ metadata_display = gr.Markdown(label="Metadata")
221
+ raw_json_display = gr.Code(label="Raw JSON", language="json")
222
+
223
+ # Connect buttons
224
+ random_btn.click(
225
+ fn=get_random_conversation,
226
+ outputs=conversation_id_input
227
+ )
228
+
229
+ load_btn.click(
230
+ fn=display_conversation,
231
+ inputs=conversation_id_input,
232
+ outputs=[conversation_display, annotator_display, metadata_display, raw_json_display]
233
+ )
234
+
235
+ conversation_id_input.submit(
236
+ fn=display_conversation,
237
+ inputs=conversation_id_input,
238
+ outputs=[conversation_display, annotator_display, metadata_display, raw_json_display]
239
+ )
240
+
241
+ # Tab 2: Dataset Statistics
242
+ with gr.Tab("Dataset Statistics"):
243
+ stats_btn = gr.Button("πŸ“Š Load Statistics", variant="primary")
244
+ stats_display = gr.Markdown(label="Dataset Statistics")
245
+
246
+ stats_btn.click(
247
+ fn=get_dataset_stats,
248
+ outputs=stats_display
249
+ )
250
+
251
+ # Tab 3: Search
252
+ with gr.Tab("Search Conversations"):
253
+ with gr.Row():
254
+ with gr.Column(scale=1):
255
+ search_query = gr.Textbox(
256
+ label="Search Query",
257
+ placeholder="Enter search term...",
258
+ interactive=True
259
+ )
260
+ search_field = gr.Dropdown(
261
+ label="Search Field",
262
+ choices=[
263
+ "first_turn_prompt",
264
+ "second_turn_prompt",
265
+ "third_turn_prompt",
266
+ "annotator_country",
267
+ "annotator_age",
268
+ "annotator_gender",
269
+ "assigned_lang"
270
+ ],
271
+ value="first_turn_prompt",
272
+ interactive=True
273
+ )
274
+ search_btn = gr.Button("πŸ” Search", variant="primary")
275
+
276
+ with gr.Column(scale=2):
277
+ search_results = gr.Markdown(label="Search Results")
278
+
279
+ search_btn.click(
280
+ fn=search_conversations,
281
+ inputs=[search_query, search_field],
282
+ outputs=search_results
283
+ )
284
+
285
+ search_query.submit(
286
+ fn=search_conversations,
287
+ inputs=[search_query, search_field],
288
+ outputs=search_results
289
+ )
290
+
291
+ # Tab 4: About
292
+ with gr.Tab("About"):
293
+ gr.Markdown("""
294
+ ## About the Facebook Community Alignment Dataset
295
+
296
+ This dataset contains conversations with multiple response options and human annotations indicating which responses are preferred by different demographic groups.
297
+
298
+ ### Dataset Structure:
299
+ - **Conversations**: Multi-turn dialogues with prompts and multiple response options
300
+ - **Annotations**: Human preferences for different response options
301
+ - **Demographics**: Annotator information including age, gender, education, political views, ethnicity, and country
302
+
303
+ ### Key Features:
304
+ - Multi-turn conversations (up to 4 turns)
305
+ - 4 response options per turn (A, B, C, D)
306
+ - Human preference annotations
307
+ - Diverse annotator demographics
308
+ - Balanced subsets for analysis
309
+
310
+ ### Use Cases:
311
+ - Studying response preferences across demographics
312
+ - Training models to generate community-aligned responses
313
+ - Analyzing conversation dynamics
314
+ - Understanding cultural and demographic differences in communication preferences
315
+
316
+ ### Citation:
317
+ If you use this dataset, please cite the original Facebook research paper.
318
+ """)
319
+
320
+ # Auto-load a random conversation on startup
321
+ demo.load(
322
+ fn=display_conversation,
323
+ inputs=conversation_id_input,
324
+ outputs=[conversation_display, annotator_display, metadata_display, raw_json_display]
325
+ )
326
+
327
+ return demo
328
+
329
+ # Create and launch the app
330
+ if __name__ == "__main__":
331
+ demo = create_interface()
332
+ demo.launch(
333
+ server_name="0.0.0.0",
334
+ server_port=7860,
335
+ share=False,
336
+ show_error=True
337
+ )