-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_session_components.py
More file actions
626 lines (521 loc) · 23.4 KB
/
process_session_components.py
File metadata and controls
626 lines (521 loc) · 23.4 KB
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
"""
UI Component builders for the Process Session tab.
This module provides builder classes for creating Gradio UI components in a modular,
testable way. Each builder class is responsible for creating a specific section of
the Process Session tab UI.
Builder Classes:
- **WorkflowHeaderBuilder**: Visual workflow stepper (Upload → Configure → Process → Review)
- **CampaignBadgeBuilder**: Campaign selection badge display
- **AudioUploadSectionBuilder**: File upload with history warnings
- **PartySelectionSectionBuilder**: Party config dropdown with character display
- **ConfigurationSectionBuilder**: Session config (speakers, language, backends, toggles)
- **ProcessingControlsBuilder**: Action buttons and status displays
- **ResultsSectionBuilder**: Transcript displays (full, IC, OOC, stats, snippets)
- **ProcessSessionTabBuilder**: Main orchestrator that combines all sections
Design Pattern:
- **Builder Pattern**: Each section is built by a dedicated builder class
- **Static Methods**: Builders use @staticmethod for stateless construction
- **Component References**: Returns dictionary of component refs for event wiring
- **Separation of Concerns**: UI structure separated from behavior (events)
Architecture Flow:
1. ProcessSessionTabBuilder receives configuration (parties, defaults, badge text)
2. Each section builder creates its Gradio components
3. Components are collected into a reference dictionary
4. Main module wires events using ProcessSessionEventWiring
5. Tab is ready for user interaction
Example:
>>> tab_builder = ProcessSessionTabBuilder(
... available_parties=["Manual Entry", "Party A", "Party B"],
... initial_defaults={"num_speakers": 4, "party_selection": "Party A"},
... campaign_badge_text="My Campaign Active"
... )
>>> component_refs = tab_builder.build_ui_components()
>>> # component_refs contains all UI elements keyed by name
Benefits:
- Testable: Each builder can be tested in isolation
- Maintainable: Easy to modify individual sections
- Reusable: Builders can be composed in different ways
- Readable: Clear separation of UI sections
See Also:
- `src.ui.process_session_tab_modern`: Main orchestration
- `src.ui.process_session_helpers`: Business logic and validation
- `src.ui.process_session_events`: Event handler wiring
- `src.ui.helpers`: Shared UI utilities and constants
"""
from typing import Any, Dict, List
import gradio as gr
from src.ui.helpers import InfoText, Placeholders, StatusMessages, UIComponents
from src.ui.constants import StatusIndicators as SI
# ============================================================================
# Workflow Header
# ============================================================================
class WorkflowHeaderBuilder:
"""Builder for the visual workflow stepper."""
@staticmethod
def build() -> gr.HTML:
"""Create workflow stepper HTML component."""
return gr.HTML(
"""
<div class="stepper">
<div class="step active">
<div class="step-number">1</div>
<div class="step-label">Upload</div>
<div class="step-connector"></div>
</div>
<div class="step">
<div class="step-number">2</div>
<div class="step-label">Configure</div>
<div class="step-connector"></div>
</div>
<div class="step">
<div class="step-number">3</div>
<div class="step-label">Process</div>
<div class="step-connector"></div>
</div>
<div class="step">
<div class="step-number">4</div>
<div class="step-label">Review</div>
</div>
</div>
"""
)
# ============================================================================
# Upload Section (Step 1)
# ============================================================================
class UploadSectionBuilder:
"""Builder for the audio upload section."""
ALLOWED_AUDIO_EXTENSIONS = [".m4a", ".mp3", ".wav", ".flac"]
def build(self) -> Dict[str, gr.Component]:
"""
Build Step 1: Upload Audio section.
Returns:
Dictionary with component references:
- audio_input: File upload component
- file_warning_display: Warning markdown for duplicate files
"""
components = {}
with gr.Group():
gr.Markdown("### Step 1: Upload Audio")
components["audio_input"] = gr.File(
label="Session Audio File",
file_types=self.ALLOWED_AUDIO_EXTENSIONS,
)
components["file_warning_display"] = gr.Markdown(
value="",
visible=False,
)
return components
# ============================================================================
# Configuration Section (Step 2)
# ============================================================================
class ConfigurationSectionBuilder:
"""Builder for the session configuration section."""
def __init__(
self,
available_parties: List[str],
initial_defaults: Dict[str, Any],
):
"""
Initialize configuration builder.
Args:
available_parties: List of party IDs to populate dropdown
initial_defaults: Default values for all configuration fields
"""
self.available_parties = available_parties
self.initial_defaults = initial_defaults
def build(self) -> Dict[str, gr.Component]:
"""
Build Step 2: Configure Session section.
Returns:
Dictionary with component references:
- session_id_input
- party_selection_input
- party_characters_display
- num_speakers_input
- language_input
- character_names_input
- player_names_input
- transcription_backend_input
- diarization_backend_input
- classification_backend_input
- skip_diarization_input
- skip_classification_input
- skip_snippets_input
- skip_knowledge_input
"""
components = {}
with gr.Group():
gr.Markdown("### Step 2: Configure Session")
# Session ID
components["session_id_input"] = gr.Textbox(
label="Session ID",
placeholder=Placeholders.SESSION_ID,
info=InfoText.SESSION_ID,
)
# Party Selection
with gr.Row():
components["party_selection_input"] = gr.Dropdown(
label="Party Configuration",
choices=self.available_parties,
value=self.initial_defaults.get("party_selection") or "Manual Entry",
info="Select an existing party profile or choose Manual Entry.",
)
components["party_characters_display"] = gr.Markdown(
value="",
visible=False,
)
# Speaker and Language Settings
with gr.Row():
components["num_speakers_input"] = gr.Slider(
minimum=2,
maximum=10,
value=self.initial_defaults.get("num_speakers", 4),
step=1,
label="Expected Speakers",
info="Helps diarization accuracy. Typical table is 3 players + 1 DM.",
)
components["language_input"] = gr.Dropdown(
label="Language",
choices=["en", "nl"],
value="nl",
info="Select the language spoken in the session.",
)
components["character_names_input"] = gr.Textbox(
label="Character Names (comma-separated)",
placeholder=Placeholders.CHARACTER_NAME,
info="Used when Manual Entry is selected.",
)
components["player_names_input"] = gr.Textbox(
label="Player Names (comma-separated)",
placeholder=Placeholders.PLAYER_NAME,
info="Optional player name mapping for manual entry.",
)
# Backend Settings (Advanced)
with gr.Accordion("Advanced Backend Settings", open=False):
components["transcription_backend_input"] = gr.Dropdown(
label="Transcription Backend",
choices=["whisper", "groq"],
value="whisper",
info="Use local Whisper or cloud Groq API.",
)
components["diarization_backend_input"] = gr.Dropdown(
label="Diarization Backend",
choices=["pyannote", "hf_api"],
value="pyannote",
info="Use local PyAnnote or cloud Hugging Face API.",
)
components["classification_backend_input"] = gr.Dropdown(
label="Classification Backend",
choices=["ollama", "groq", "colab"],
value="colab",
info="Use local Ollama, cloud Groq API, or Google Colab GPU.",
)
# Pipeline Control
components["run_until_stage_input"] = gr.Dropdown(
label="Run Pipeline Until",
choices=[
("Full Pipeline (All Stages)", "full"),
("Stage 4: Transcription Only", "stage_4"),
("Stage 5: Through Diarization", "stage_5"),
("Stage 6: Through Classification", "stage_6"),
("Stage 7: Through Output Generation (Skip Snippets & Knowledge)", "stage_7"),
],
value="full",
info="Control which stages of the pipeline to execute",
)
# Skip Options (Advanced)
with gr.Accordion("Advanced Skip Options", open=False):
gr.Markdown("*These options are auto-set by 'Run Pipeline Until' but can be manually overridden*")
with gr.Row():
components["skip_diarization_input"] = gr.Checkbox(
label="Skip Speaker Identification",
value=self.initial_defaults.get("skip_diarization", False),
info="Saves time but all segments will be UNKNOWN.",
)
components["skip_classification_input"] = gr.Checkbox(
label="Skip IC/OOC Classification",
value=self.initial_defaults.get("skip_classification", False),
info="Disables in-character versus out-of-character separation.",
)
components["skip_snippets_input"] = gr.Checkbox(
label="Skip Snippet Export",
value=self.initial_defaults.get("skip_snippets", True),
info="Skip exporting WAV snippets to save disk space.",
)
components["skip_knowledge_input"] = gr.Checkbox(
label="Skip Knowledge Extraction",
value=self.initial_defaults.get("skip_knowledge", False),
info="Disable automatic quest/NPC extraction.",
)
with gr.Accordion("Advanced Processing Options", open=False):
with gr.Row():
components["enable_audit_mode_input"] = gr.Checkbox(
label="Enable Audit Mode",
value=False,
info="Save detailed classification prompts and responses for reproducibility. Increases disk usage but enables debugging.",
)
components["redact_prompts_input"] = gr.Checkbox(
label="Redact Prompts in Logs",
value=False,
info="When audit mode is enabled, redact full dialogue text from audit logs.",
)
with gr.Row():
components["generate_scenes_input"] = gr.Checkbox(
label="Generate Scene Bundles",
value=True,
info="Automatically detect and bundle segments into narrative scenes.",
)
components["scene_summary_mode_input"] = gr.Dropdown(
choices=["template", "llm", "none"],
value="template",
label="Scene Summary Mode",
info="How to generate scene summaries (template=fast, llm=detailed, none=skip)",
)
return components
# ============================================================================
# Processing Controls Section (Step 3)
# ============================================================================
class ProcessingControlsBuilder:
"""Builder for processing controls and status displays."""
def build(self) -> Dict[str, gr.Component]:
"""
Build Step 3: Process section with controls and status displays.
Returns:
Dictionary with component references:
- preflight_btn
- process_btn
- overall_progress_display
- status_output
- transcription_progress
- runtime_accordion
- stage_progress_display
- event_log_display
- transcription_timer
- should_process_state
"""
components = {}
with gr.Group():
gr.Markdown("### Step 3: Process")
components["preflight_btn"] = UIComponents.create_action_button(
"Run Preflight Checks",
variant="secondary",
size="md",
full_width=True,
)
components["process_btn"] = UIComponents.create_action_button(
"Start Processing",
variant="primary",
size="lg",
full_width=True,
)
components["cancel_btn"] = UIComponents.create_action_button(
"Cancel Processing",
variant="stop",
size="md",
full_width=True,
visible=False,
)
# Overall Progress Indicator (prominent, visible during processing)
components["overall_progress_display"] = gr.Markdown(
value="",
visible=False,
)
components["status_output"] = gr.Markdown(
value=StatusMessages.info(
"Ready",
"Provide a session ID and audio file, then click Start Processing."
)
)
components["transcription_progress"] = gr.Markdown(
value="",
visible=False,
)
# Enhanced Runtime Updates Section
with gr.Accordion("Runtime Updates & Event Log", open=False) as runtime_accordion:
gr.Markdown("**Live processing status, stage progress, and detailed event log**")
# Stage Progress Overview
components["stage_progress_display"] = gr.Markdown(
value="",
visible=False,
)
# Persistent Event Log
components["event_log_display"] = gr.Textbox(
label="Event Log",
lines=15,
max_lines=30,
value="",
interactive=False,
# show_copy_button=False, # Deprecated in newer Gradio
elem_classes=["event-log-textbox"],
)
components["runtime_accordion"] = runtime_accordion
components["transcription_timer"] = gr.Timer(value=2.0)
# State for processing flow control
components["should_process_state"] = gr.State(value=False)
return components
# ============================================================================
# Results Section (Step 4)
# ============================================================================
class ResultsSectionBuilder:
"""Builder for the results display section."""
def build(self) -> Dict[str, gr.Component]:
"""
Build Step 4: Review Results section.
Returns:
Dictionary with component references:
- results_section (Group)
- full_output (HighlightedText)
- ic_output
- ooc_output
- stats_output
- snippet_output
- scroll_trigger
"""
components = {}
with gr.Group(visible=False, elem_id="process-results-section") as results_section:
gr.Markdown("### Step 4: Review Results")
# IMPROVEMENT: Use HighlightedText for a richer, color-coded transcript view.
color_map = {
"CHARACTER": "blue",
"DM_NARRATION": "gray",
"NPC_DIALOGUE": "purple",
"OOC_OTHER": "red",
}
components["full_output"] = gr.HighlightedText(
label="Full Transcript (Color-Coded by Classification)",
color_map=color_map,
interactive=False,
show_legend=True,
)
components["ic_output"] = gr.Textbox(label="In-Character Transcript", lines=10)
components["ooc_output"] = gr.Textbox(label="Out-of-Character Transcript", lines=10)
components["stats_output"] = gr.Markdown()
components["snippet_output"] = gr.Markdown()
components["results_section"] = results_section
# Auto-scroll JavaScript component (hidden, triggers when results appear)
components["scroll_trigger"] = gr.HTML(visible=False)
return components
# ============================================================================
# Resume from Intermediate Section
# ============================================================================
class ResumeFromIntermediateBuilder:
"""Builder for resume from intermediate outputs section."""
def build(self) -> Dict[str, gr.Component]:
"""
Build Resume from Intermediate section.
Allows users to resume processing from saved intermediate outputs.
"""
from src.ui.intermediate_resume_helper import discover_sessions_with_intermediates
components = {}
with gr.Accordion("🔄 Resume from Intermediate Outputs", open=False):
gr.Markdown(
"""
Resume processing from a previously saved intermediate stage. This allows you to:
- Edit intermediate outputs manually and reprocess
- Test different backends on the same data
- Skip expensive stages that are already complete
"""
)
# Discover sessions button and dropdown
with gr.Row():
components["resume_refresh_btn"] = UIComponents.create_action_button(
"🔍 Find Sessions",
variant="secondary",
size="sm",
)
components["resume_session_dropdown"] = gr.Dropdown(
label="Session to Resume",
choices=[],
value=None,
interactive=True,
info="Select a session with intermediate outputs",
)
components["resume_stage_dropdown"] = gr.Dropdown(
label="Resume from Stage",
choices=[
("Stage 4: Merged Transcript → Run Diarization, Classification, Outputs", 4),
("Stage 5: Diarization → Run Classification, Outputs", 5),
("Stage 6: Classification → Regenerate Outputs Only", 6),
],
value=5,
interactive=True,
info="Which stage to resume from",
)
components["resume_session_info"] = gr.Markdown(
value=StatusMessages.info(
"Session Info",
"Click 'Find Sessions' to discover available sessions, then select one to see details."
)
)
with gr.Row():
components["resume_process_btn"] = UIComponents.create_action_button(
"▶️ Resume Processing",
variant="primary",
size="lg",
)
components["resume_status"] = gr.Markdown(
value=""
)
return components
# ============================================================================
# Main Tab Builder
# ============================================================================
class ProcessSessionTabBuilder:
"""
Main builder that orchestrates all section builders.
This class coordinates the creation of all UI components for the
Process Session tab using the individual section builders.
"""
def __init__(
self,
available_parties: List[str],
initial_defaults: Dict[str, Any],
campaign_badge_text: str,
):
"""
Initialize the main tab builder.
Args:
available_parties: List of party IDs
initial_defaults: Default values for configuration
campaign_badge_text: Initial campaign badge markdown
"""
self.available_parties = available_parties
self.initial_defaults = initial_defaults
self.campaign_badge_text = campaign_badge_text
def build_ui_components(self) -> Dict[str, gr.Component]:
"""
Build all UI components for the Process Session tab.
Returns:
Dictionary containing all component references organized by section.
"""
all_components = {}
# Create workflow header
WorkflowHeaderBuilder.build()
# Tab header
gr.Markdown(
"""
# Process Session Recording
Upload an audio file, apply campaign defaults, and run the pipeline.
"""
)
# Campaign badge
badge_value = self.campaign_badge_text or StatusMessages.info(
"Campaign",
"No campaign selected. Use the Campaign Launcher above to choose one."
)
all_components["campaign_badge"] = gr.Markdown(value=badge_value)
# Build each section
upload_builder = UploadSectionBuilder()
all_components.update(upload_builder.build())
config_builder = ConfigurationSectionBuilder(
self.available_parties,
self.initial_defaults
)
all_components.update(config_builder.build())
controls_builder = ProcessingControlsBuilder()
all_components.update(controls_builder.build())
results_builder = ResultsSectionBuilder()
all_components.update(results_builder.build())
resume_builder = ResumeFromIntermediateBuilder()
all_components.update(resume_builder.build())
return all_components