-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmain.py
More file actions
1831 lines (1572 loc) · 77.3 KB
/
main.py
File metadata and controls
1831 lines (1572 loc) · 77.3 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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import os
import requests
import warnings
import logging
import io
import time
import pandas as pd
# Suppress specific warnings
warnings.filterwarnings("ignore", message=".*is not a valid config option.*")
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Attempt to import torch safely
try:
import torch
# Suppress specific PyTorch warnings
import warnings
warnings.filterwarnings('ignore', category=UserWarning, module='torch')
except ImportError:
logger.warning("PyTorch not found. Some ML features may be limited.")
torch = None
from utils import (
extract_audio, transcribe_audio, is_valid_video_format,
translate_text, get_available_languages, export_to_srt, export_to_vtt,
export_to_markdown, export_to_json
)
from database import TranscriptionDB
import ai_persona
from video_player import render_interactive_player, render_simple_transcript_with_timestamps, render_transcript_with_speakers
from task_presets import (
TASK_PRESETS, get_task_presets_by_category, get_category_info,
generate_task_prompt, export_content_to_markdown
)
from batch_processor import (
BatchJobQueue, JobStatus, get_batch_queue, start_batch_processing,
process_video_job
)
from speaker_diarization import (
SpeakerDiarizer, SimpleDiarizer, SpeakerSegment, SpeakerStats,
get_diarizer, format_speaker_transcript, export_with_speakers_srt,
export_with_speakers_vtt, create_manual_segments
)
from rag_citations import (
TranscriptRAG, RAGPersonaChat, RAGResponse, Citation,
format_response_with_citations, get_transcript_rag
)
from multi_speaker_persona import (
MultiSpeakerPersona, SpeakerProfile, PanelResponse,
format_panel_response, get_multi_speaker_persona
)
from typing import Tuple, Optional
import json
import tempfile
def initialize_session_state():
"""Initialize session state variables."""
if 'messages' not in st.session_state:
st.session_state.messages = []
# Batch processing state
if 'batch_queue' not in st.session_state:
st.session_state.batch_queue = get_batch_queue()
if 'batch_processing_started' not in st.session_state:
st.session_state.batch_processing_started = False
if 'batch_max_concurrent' not in st.session_state:
st.session_state.batch_max_concurrent = 1
# Default settings
default_settings = {
'api_base': "http://localhost:11434",
'model': "mistral:instruct",
'temperature': 0.7,
'top_p': 0.9,
'top_k': 40,
'repeat_penalty': 1.1,
'max_tokens': 1024,
'context_window': 4096
}
# Try to load saved settings, fall back to defaults if not found
if 'ollama_settings' not in st.session_state:
settings_file = "settings.json"
try:
with open(settings_file, 'r') as f:
saved_settings = json.load(f)
# Merge saved settings with defaults (in case new settings were added)
st.session_state.ollama_settings = {**default_settings, **saved_settings}
except (FileNotFoundError, json.JSONDecodeError):
st.session_state.ollama_settings = default_settings.copy()
if 'show_settings' not in st.session_state:
st.session_state.show_settings = False
def save_settings():
"""Save current settings to a JSON file."""
settings_file = "settings.json"
try:
with open(settings_file, 'w') as f:
json.dump(st.session_state.ollama_settings, f, indent=4)
return True
except Exception as e:
print(f"Error saving settings: {str(e)}")
return False
def load_settings():
"""Load settings from JSON file."""
settings_file = "settings.json"
try:
with open(settings_file, 'r') as f:
saved_settings = json.load(f)
# Update session state with saved settings
st.session_state.ollama_settings.update(saved_settings)
# No rerun needed here as this is called during initialization
return True
except FileNotFoundError:
return False
except Exception as e:
print(f"Error loading settings: {str(e)}")
return False
def render_sidebar_settings():
"""Render Ollama settings in the sidebar."""
# Ollama API settings in a collapsible section
with st.sidebar.expander("🤖 AI Settings", expanded=False):
st.subheader("Ollama Configuration")
# API Base URL
api_base = st.text_input(
"API Base URL",
value=st.session_state.ollama_settings['api_base'],
help="The base URL for your Ollama instance"
)
# Fetch available models
try:
available_models = ai_persona.PersonaAnalyzer.get_available_models(api_base)
if not available_models:
available_models = ["mistral:instruct"]
st.error("⚠️ No models found. Is Ollama running?")
except requests.RequestException as e:
available_models = ["mistral:instruct"]
st.error(f"⚠️ Network error fetching models: {e}")
except Exception as e:
available_models = ["mistral:instruct"]
st.error(f"⚠️ Unexpected error fetching models: {e}")
# Ensure the current model is in the list
current_model = st.session_state.ollama_settings['model']
if current_model not in available_models:
available_models.append(current_model)
# Model selection
model = st.selectbox(
"Model",
options=available_models,
index=available_models.index(current_model),
help="Select the AI model to use for persona generation and chat"
)
# Advanced model parameters
st.subheader("Model Parameters")
col1, col2 = st.columns(2)
with col1:
temperature = st.slider(
"Temperature",
min_value=0.0,
max_value=2.0,
value=st.session_state.ollama_settings['temperature'],
step=0.1,
help="Controls randomness in responses"
)
top_p = st.slider(
"Top P",
min_value=0.0,
max_value=1.0,
value=st.session_state.ollama_settings['top_p'],
step=0.1,
help="Nucleus sampling threshold"
)
repeat_penalty = st.slider(
"Repeat Penalty",
min_value=1.0,
max_value=2.0,
value=st.session_state.ollama_settings['repeat_penalty'],
step=0.1,
help="Penalty for repeating tokens"
)
with col2:
top_k = st.slider(
"Top K",
min_value=1,
max_value=100,
value=st.session_state.ollama_settings['top_k'],
help="Limits vocabulary in responses"
)
max_tokens = st.slider(
"Max Tokens",
min_value=128,
max_value=4096,
value=st.session_state.ollama_settings['max_tokens'],
step=128,
help="Maximum response length"
)
context_window = st.slider(
"Context Window",
min_value=512,
max_value=8192,
value=st.session_state.ollama_settings['context_window'],
step=512,
help="Token context window size"
)
# Save settings button
col1, col2 = st.columns(2)
with col1:
if st.button("💾 Save Settings"):
if save_settings():
st.success("Settings saved!")
else:
st.error("Failed to save settings")
with col2:
if st.button("🔄 Reset Defaults"):
st.session_state.ollama_settings = {
'api_base': "http://localhost:11434",
'model': "mistral:instruct",
'temperature': 0.7,
'top_p': 0.9,
'top_k': 40,
'repeat_penalty': 1.1,
'max_tokens': 1024,
'context_window': 4096
}
save_settings() # Save the default settings
st.rerun()
# Update settings if changed
current_settings = {
'api_base': api_base,
'model': model,
'temperature': temperature,
'top_p': top_p,
'top_k': top_k,
'repeat_penalty': repeat_penalty,
'max_tokens': max_tokens,
'context_window': context_window
}
# Only compare keys that exist in current_settings to avoid infinite rerun
settings_changed = any(
st.session_state.ollama_settings.get(k) != v
for k, v in current_settings.items()
)
if settings_changed:
st.session_state.ollama_settings.update(current_settings)
save_settings() # Auto-save when settings change
st.rerun()
# Initialize database
db = TranscriptionDB()
# Client Management section
st.sidebar.header("Client Management")
client_management_tab = st.sidebar.expander("Manage Clients", expanded=False)
with client_management_tab:
render_client_management(db)
def render_client_management(db):
"""Render the client management section."""
st.header("🤝 Client Management")
# Get current list of clients
clients = db.get_all_clients()
# Client List Section
st.subheader("Existing Clients")
if not clients:
st.info("No clients found. Add a new client below.")
else:
# Create a DataFrame for clients
client_df = pd.DataFrame(clients, columns=['ID', 'Name', 'Email'])
st.dataframe(client_df, hide_index=True)
# Add Client Form with a unique key
st.subheader("Add New Client")
with st.form(key=f"add_client_form_{int(time.time())}"):
name = st.text_input("Client Name")
email = st.text_input("Client Email")
submit_button = st.form_submit_button("Add Client")
if submit_button:
if not name or not email:
st.error("Please provide both name and email.")
else:
try:
client_id = db.add_client(name, email)
st.success(f"Client '{name}' added successfully!")
# Force a rerun to refresh the client list
st.rerun()
except Exception as e:
st.error(f"Error adding client: {str(e)}")
# Delete Client Section
st.subheader("Delete Client")
client_options = [f"{client[1]} ({client[2]})" for client in clients] if clients else []
if client_options:
selected_client = st.selectbox("Select Client to Delete", client_options)
# Two-step confirmation for deletion
if 'delete_client_confirmed' not in st.session_state:
st.session_state.delete_client_confirmed = False
if st.button("Delete Client"):
if not st.session_state.delete_client_confirmed:
st.warning(f"Are you sure you want to delete {selected_client}? This action cannot be undone.")
st.session_state.delete_client_confirmed = True
else:
# Find the client ID
client_to_delete = next(
client for client in clients
if f"{client[1]} ({client[2]})" == selected_client
)
try:
db.delete_client(client_to_delete[0])
st.success(f"Client {selected_client} deleted successfully!")
# Reset confirmation and force rerun
st.session_state.delete_client_confirmed = False
st.rerun()
except Exception as e:
st.error(f"Error deleting client: {str(e)}")
st.session_state.delete_client_confirmed = False
else:
st.info("No clients available to delete.")
def get_persona_analyzer() -> ai_persona.PersonaAnalyzer:
"""Get a PersonaAnalyzer instance with current settings."""
options = {
"temperature": st.session_state.ollama_settings['temperature'],
"top_p": st.session_state.ollama_settings['top_p'],
"top_k": st.session_state.ollama_settings['top_k'],
"repeat_penalty": st.session_state.ollama_settings['repeat_penalty'],
"num_predict": st.session_state.ollama_settings['max_tokens'],
"num_ctx": st.session_state.ollama_settings['context_window']
}
return ai_persona.PersonaAnalyzer(
model=st.session_state.ollama_settings['model'],
api_base=st.session_state.ollama_settings['api_base'],
options=options
)
def get_client_list():
"""Get list of clients for dropdown."""
db = TranscriptionDB()
clients = db.get_all_clients()
return {f"{client[1]} ({client[2]})": client[0] for client in clients}
def check_environment():
"""Check if all required environment variables are set."""
try:
# Check if Ollama is running by making a test request
response = requests.get("http://localhost:11434/api/version")
if response.status_code != 200:
st.error("❌ Ollama server is not running. Please start Ollama first.")
st.stop()
st.success("✅ Ollama server is running")
return True
except requests.exceptions.ConnectionError:
st.error("❌ Ollama server is not running. Please start Ollama first.")
st.stop()
return False
def regenerate_persona_for_transcription(transcription_id: int, original_text: str, db: TranscriptionDB) -> Tuple[bool, Optional[str]]:
"""Regenerate persona prompt for an existing transcription."""
analyzer = get_persona_analyzer()
try:
persona_name, system_prompt = analyzer.analyze_transcript(original_text)
if persona_name and system_prompt and len(system_prompt.strip()) > 0:
success = db.update_persona_prompt(transcription_id, persona_name, system_prompt)
if success:
return True, persona_name
return False, None
except Exception as e:
print(f"Error regenerating persona: {str(e)}")
return False, None
def render_task_presets(db: TranscriptionDB, transcription_id: int, original_text: str, context: str = "default"):
"""
Render the task presets section with one-click action buttons.
Args:
db (TranscriptionDB): Database connection
transcription_id (int): ID of the transcription
original_text (str): Original transcribed text
context (str, optional): Context of where this is being called.
"""
st.markdown("### ⚡ Quick Actions")
st.caption("One-click tasks to generate structured content from the transcript")
# Get presets by category
categories = get_task_presets_by_category()
category_info = get_category_info()
# Create tabs for each category
category_tabs = st.tabs([f"{category_info[cat]['icon']} {category_info[cat]['name']}" for cat in categories.keys()])
for tab, (category_key, presets) in zip(category_tabs, categories.items()):
with tab:
# Create columns for preset buttons (3 per row)
cols = st.columns(3)
for idx, preset in enumerate(presets):
with cols[idx % 3]:
button_key = f"preset_{preset.id}_{transcription_id}_{context}"
if st.button(f"{preset.icon} {preset.name}", key=button_key, help=preset.description, use_container_width=True):
# Store which preset was clicked
st.session_state[f"active_preset_{transcription_id}_{context}"] = preset.id
st.session_state[f"generating_{transcription_id}_{context}"] = True
# Handle preset generation
generating_key = f"generating_{transcription_id}_{context}"
active_preset_key = f"active_preset_{transcription_id}_{context}"
if st.session_state.get(generating_key, False):
preset_id = st.session_state.get(active_preset_key)
if preset_id and preset_id in TASK_PRESETS:
preset = TASK_PRESETS[preset_id]
with st.spinner(f"Generating {preset.name}..."):
try:
# Generate the prompt with transcript
full_prompt = generate_task_prompt(preset_id, original_text)
# Use the AI to generate content
analyzer = get_persona_analyzer()
generated_content = analyzer.generate_response(
f"You are an expert content analyst. Analyze the provided transcript and generate the requested output format.",
full_prompt
)
# Save to database
content_id = db.add_generated_content(transcription_id, preset_id, generated_content)
st.success(f"✅ {preset.name} generated and saved!")
# Reset generation state
st.session_state[generating_key] = False
st.session_state[active_preset_key] = None
st.rerun()
except Exception as e:
st.error(f"Error generating content: {str(e)}")
st.session_state[generating_key] = False
# Display previously generated content
st.markdown("---")
st.markdown("### 📂 Generated Content")
generated_items = db.get_generated_content(transcription_id)
if not generated_items:
st.info("No content generated yet. Click a Quick Action button above to get started!")
else:
for item in generated_items:
content_id, _, task_type, content, created_at = item
preset = TASK_PRESETS.get(task_type)
preset_name = preset.name if preset else task_type
preset_icon = preset.icon if preset else "📄"
with st.expander(f"{preset_icon} {preset_name} - {created_at}", expanded=False):
st.markdown(content)
# Export and delete buttons
col1, col2, col3 = st.columns([1, 1, 2])
with col1:
# Export as Markdown
md_export = export_content_to_markdown(content, preset_name)
st.download_button(
label="📥 Export MD",
data=md_export,
file_name=f"{task_type}_{created_at.replace(':', '-').replace(' ', '_')}.md",
mime="text/markdown",
key=f"export_md_{content_id}_{context}"
)
with col2:
# Delete button
delete_key = f"delete_content_{content_id}_{context}"
if st.button("🗑️ Delete", key=delete_key):
st.session_state[f"confirm_delete_{content_id}"] = True
# Confirmation for delete
if st.session_state.get(f"confirm_delete_{content_id}", False):
st.warning("Are you sure you want to delete this content?")
conf_col1, conf_col2 = st.columns(2)
with conf_col1:
if st.button("Yes, delete", key=f"confirm_yes_{content_id}_{context}"):
db.delete_generated_content(content_id)
st.session_state[f"confirm_delete_{content_id}"] = False
st.rerun()
with conf_col2:
if st.button("Cancel", key=f"confirm_no_{content_id}_{context}"):
st.session_state[f"confirm_delete_{content_id}"] = False
st.rerun()
def render_batch_upload(db: TranscriptionDB, client_id: int):
"""Render the batch upload and job queue interface."""
st.markdown("### 📁 Batch Upload Queue")
st.caption("Upload multiple videos at once and process them in the background")
batch_queue = st.session_state.batch_queue
# Settings row
col1, col2, col3 = st.columns([2, 2, 1])
with col1:
max_concurrent = st.selectbox(
"Processing Mode",
options=[1, 2, 3],
index=0,
format_func=lambda x: "Sequential (1 at a time)" if x == 1 else f"Parallel ({x} at a time)",
help="How many videos to process simultaneously"
)
st.session_state.batch_max_concurrent = max_concurrent
with col2:
include_timestamps = st.checkbox("Include Timestamps", value=True, key="batch_timestamps")
with col3:
# Start/Stop processing button
if not st.session_state.batch_processing_started:
if st.button("▶️ Start Processing", use_container_width=True):
batch_queue.set_max_concurrent(max_concurrent)
batch_queue.start_workers(process_video_job)
st.session_state.batch_processing_started = True
st.rerun()
else:
if st.button("⏹️ Stop Processing", use_container_width=True):
batch_queue.stop_workers()
st.session_state.batch_processing_started = False
st.rerun()
st.markdown("---")
# File uploader with multiple files
uploaded_files = st.file_uploader(
"Drop multiple videos here",
type=['mp4', 'avi', 'mov', 'mkv', 'm4a'],
accept_multiple_files=True,
key="batch_uploader"
)
if uploaded_files:
if st.button(f"📤 Add {len(uploaded_files)} file(s) to Queue", use_container_width=True):
added_count = 0
for uploaded_file in uploaded_files:
try:
# Save file to temp location
ext = os.path.splitext(uploaded_file.name)[1]
with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as tmp_file:
tmp_file.write(uploaded_file.read())
tmp_path = tmp_file.name
# Add to queue
batch_queue.add_job(
filename=uploaded_file.name,
file_path=tmp_path,
client_id=client_id,
include_timestamps=include_timestamps
)
added_count += 1
except Exception as e:
st.error(f"Error adding {uploaded_file.name}: {str(e)}")
if added_count > 0:
st.success(f"Added {added_count} file(s) to the queue!")
# Start processing if not already started
if not st.session_state.batch_processing_started:
batch_queue.set_max_concurrent(max_concurrent)
batch_queue.start_workers(process_video_job)
st.session_state.batch_processing_started = True
st.rerun()
st.markdown("---")
# Queue statistics
stats = batch_queue.get_queue_stats(client_id)
stat_cols = st.columns(5)
with stat_cols[0]:
st.metric("🕐 Pending", stats['pending'])
with stat_cols[1]:
st.metric("⏳ Processing", stats['processing'])
with stat_cols[2]:
st.metric("✅ Complete", stats['complete'])
with stat_cols[3]:
st.metric("❌ Failed", stats['failed'])
with stat_cols[4]:
st.metric("📊 Total", stats['total'])
# Refresh button
col1, col2 = st.columns([3, 1])
with col2:
if st.button("🔄 Refresh", use_container_width=True):
st.rerun()
with col1:
if stats['complete'] + stats['failed'] + stats['cancelled'] > 0:
if st.button("🧹 Clear Completed", use_container_width=True):
batch_queue.clear_completed_jobs(client_id)
st.rerun()
st.markdown("---")
# Job list
jobs = batch_queue.get_all_jobs(client_id=client_id)
if not jobs:
st.info("No jobs in queue. Upload some videos to get started!")
return
for job in jobs:
with st.container():
# Status icon and color
status_icons = {
JobStatus.PENDING: ("🕐", "Pending"),
JobStatus.PROCESSING: ("⏳", "Processing"),
JobStatus.COMPLETE: ("✅", "Complete"),
JobStatus.FAILED: ("❌", "Failed"),
JobStatus.CANCELLED: ("🚫", "Cancelled")
}
icon, status_label = status_icons.get(job.status, ("❓", "Unknown"))
col1, col2, col3 = st.columns([3, 1, 1])
with col1:
st.markdown(f"**{icon} {job.filename}**")
if job.status == JobStatus.PROCESSING:
st.progress(job.progress / 100, text=f"Processing... {job.progress:.0f}%")
elif job.status == JobStatus.FAILED and job.error_message:
st.error(f"Error: {job.error_message}")
elif job.status == JobStatus.COMPLETE and job.transcription_id:
st.caption(f"Transcription ID: {job.transcription_id}")
with col2:
st.caption(status_label)
if job.created_at:
st.caption(job.created_at.strftime("%H:%M:%S"))
with col3:
if job.status == JobStatus.COMPLETE and job.transcription_id:
if st.button("👁️ View", key=f"view_job_{job.id}"):
st.session_state['view_transcription_id'] = job.transcription_id
st.rerun()
elif job.status == JobStatus.FAILED:
if st.button("🔄 Retry", key=f"retry_job_{job.id}"):
batch_queue.retry_job(job.id)
st.rerun()
elif job.status == JobStatus.PENDING:
if st.button("❌ Cancel", key=f"cancel_job_{job.id}"):
batch_queue.cancel_job(job.id)
st.rerun()
st.markdown("---")
def render_persona_chat(db: TranscriptionDB, transcription_id: int, original_text: str, context: str = "default"):
"""
Render the persona chat interface with task presets.
Args:
db (TranscriptionDB): Database connection
transcription_id (int): ID of the transcription
original_text (str): Original transcribed text
context (str, optional): Context of where this is being called. Defaults to "default".
"""
# Initialize session state for messages if not exists
if 'messages' not in st.session_state:
st.session_state.messages = []
# Get persona data
persona_data = db.get_persona_prompt(transcription_id)
# If no persona exists, try to generate one
if not persona_data:
with st.spinner("Generating persona..."):
success, new_name = generate_persona_for_transcription(transcription_id, original_text, db)
if success:
persona_data = db.get_persona_prompt(transcription_id)
else:
st.error("Failed to generate persona. Please try again.")
return
# If still no persona, exit
if not persona_data:
st.warning("No persona could be generated for this transcription.")
return
persona_name, system_prompt = persona_data
# Create a unique session state key for this transcription's messages
messages_key = f"messages_{transcription_id}_{context}"
if messages_key not in st.session_state:
st.session_state[messages_key] = []
# Display the system prompt in a container with toggle
col1, col2 = st.columns([3, 1])
with col1:
st.markdown(f"**Persona Name:** {persona_name}")
with col2:
# Use a unique key combining transcription_id and context
regen_key = f"regen_{transcription_id}_{context}"
if st.button("🔄 Regenerate", key=regen_key):
with st.spinner("Regenerating persona..."):
success, new_name = regenerate_persona_for_transcription(transcription_id, original_text, db)
if success:
st.success(f"Regenerated persona as '{new_name}'!")
st.rerun()
else:
st.error("Failed to regenerate persona. Please try again.")
if "show_prompt" not in st.session_state:
st.session_state.show_prompt = False
# Use a unique key for toggle button
toggle_key = f"toggle_{transcription_id}_{context}"
if st.button("Toggle Persona Details", key=toggle_key):
st.session_state.show_prompt = not st.session_state.show_prompt
if st.session_state.show_prompt:
st.markdown("**System Prompt:**")
# Use a unique key for text area
prompt_key = f"prompt_{transcription_id}_{context}"
st.text_area("", system_prompt, height=100, disabled=True, key=prompt_key)
st.markdown("---")
# Add Task Presets section
render_task_presets(db, transcription_id, original_text, context)
st.markdown("---")
st.markdown("### 💬 Chat with Persona")
# RAG Settings (using checkbox toggle to avoid nested expander)
rag_settings_key = f"rag_settings_{transcription_id}_{context}"
show_citation_settings = st.checkbox("🔍 Citation Settings", key=f"show_citation_{transcription_id}_{context}")
# Default values
use_only_transcript = True
enable_citations = True
if show_citation_settings:
st.caption("Configure how citations and transcript context are used")
col_rag1, col_rag2 = st.columns(2)
with col_rag1:
use_only_transcript_key = f"use_only_transcript_{transcription_id}_{context}"
use_only_transcript = st.checkbox(
"Use only video content",
value=True,
key=use_only_transcript_key,
help="When enabled, responses will only use information from the video transcript. "
"When disabled, the AI may use general knowledge if the answer isn't in the video."
)
with col_rag2:
enable_citations_key = f"enable_citations_{transcription_id}_{context}"
enable_citations = st.checkbox(
"Enable RAG citations",
value=True,
key=enable_citations_key,
help="When enabled, responses will include timestamped citations from the transcript."
)
# RAG Index Status
rag = get_transcript_rag()
is_indexed = rag.is_indexed(transcription_id)
chunk_count = rag.get_chunk_count(transcription_id) if is_indexed else 0
if is_indexed:
st.success(f"✅ Transcript indexed ({chunk_count} chunks)")
else:
st.warning("⚠️ Transcript not indexed for citations")
index_btn_key = f"index_btn_{transcription_id}_{context}"
if st.button("📚 Index Transcript for Citations", key=index_btn_key):
with st.spinner("Indexing transcript..."):
try:
indexed_count = rag.index_transcript(transcription_id, original_text)
st.success(f"Indexed {indexed_count} chunks!")
st.rerun()
except Exception as e:
st.error(f"Indexing failed: {str(e)}")
# Chat interface
for message in st.session_state[messages_key]:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Show citations if available
if "citations" in message and message["citations"]:
with st.expander("📍 Citations", expanded=False):
for citation in message["citations"]:
st.markdown(f"**[{citation['timestamp']}]** _{citation['text'][:150]}..._")
# Use a unique key for chat input
chat_input_key = f"chat_input_{transcription_id}_{context}"
if prompt := st.chat_input("Ask a question...", key=chat_input_key):
with st.chat_message("user"):
st.markdown(prompt)
st.session_state[messages_key].append({"role": "user", "content": prompt})
with st.chat_message("assistant"):
# Check if RAG is enabled and transcript is indexed
if enable_citations and is_indexed:
# Use RAG-augmented chat
rag_chat = RAGPersonaChat(
rag=rag,
model=st.session_state.get("selected_model", "mistral:instruct"),
api_base=st.session_state.get("ollama_api_base", "http://localhost:11434")
)
with st.spinner("Searching transcript and generating response..."):
rag_response = rag_chat.generate_response(
transcription_id=transcription_id,
persona_prompt=system_prompt,
user_query=prompt,
use_only_transcript=use_only_transcript,
top_k=5
)
# Display the response
st.markdown(rag_response.response)
# Show confidence indicator
if rag_response.confidence >= 0.7:
confidence_color = "green"
confidence_label = "High confidence"
elif rag_response.confidence >= 0.4:
confidence_color = "orange"
confidence_label = "Medium confidence"
else:
confidence_color = "red"
confidence_label = "Low confidence"
st.markdown(f"<small style='color: {confidence_color}'>🎯 {confidence_label} ({rag_response.confidence:.0%})</small>",
unsafe_allow_html=True)
if rag_response.used_general_knowledge:
st.info("ℹ️ This response includes general knowledge, not just video content.")
# Show citations in expander
if rag_response.citations:
with st.expander("📍 View Citations", expanded=True):
for citation in rag_response.citations:
col_ts, col_txt = st.columns([1, 4])
with col_ts:
st.markdown(f"**[{citation.timestamp}]**")
with col_txt:
st.markdown(f"_{citation.text}_")
# Store message with citations
citations_data = [
{"timestamp": c.timestamp, "text": c.text, "score": c.relevance_score}
for c in rag_response.citations
]
st.session_state[messages_key].append({
"role": "assistant",
"content": rag_response.response,
"citations": citations_data,
"confidence": rag_response.confidence
})
else:
# Fallback to standard persona chat without RAG
analyzer = get_persona_analyzer()
response = analyzer.generate_response(system_prompt, prompt)
st.markdown(response)
st.session_state[messages_key].append({"role": "assistant", "content": response})
def render_multi_speaker_persona_chat(db: TranscriptionDB, transcription_id: int, original_text: str, context: str = "default"):
"""Render multi-speaker persona chat with individual and panel modes."""
multi_speaker = get_multi_speaker_persona()
# Load or parse speaker profiles
if multi_speaker.has_speaker_profiles(transcription_id):
speakers = multi_speaker.load_speaker_profiles(transcription_id)
else:
# Parse speakers from transcript and save
speakers = multi_speaker.parse_diarized_transcript(original_text)
if speakers:
# Generate persona prompts for each speaker
for speaker_id, speaker in speakers.items():
speaker.persona_prompt = multi_speaker.generate_persona_prompt(speaker)
speaker.topics = multi_speaker.extract_speaker_topics(speaker)
multi_speaker.save_speaker_profiles(transcription_id, speakers)
if not speakers:
st.warning("No speakers detected in this transcript. Use regular persona chat instead.")
return
# Speaker overview
st.markdown("### 👥 Detected Speakers")
speaker_cols = st.columns(min(len(speakers), 4))
speaker_list = list(speakers.values())
for idx, speaker in enumerate(speaker_list):
with speaker_cols[idx % len(speaker_cols)]:
with st.container():
st.markdown(f"**{speaker.display_name}**")
st.caption(f"{speaker.word_count} words • {len(speaker.transcript_segments)} segments")
if speaker.topics:
st.caption(f"Topics: {', '.join(speaker.topics[:3])}")
# Allow renaming speakers (using checkbox toggle to avoid nested expander)
show_rename = st.checkbox("✏️ Rename Speakers", key=f"show_rename_{transcription_id}_{context}")
if show_rename:
rename_cols = st.columns(2)
for idx, speaker in enumerate(speaker_list):
with rename_cols[idx % 2]:
new_name_key = f"rename_{speaker.speaker_id}_{transcription_id}_{context}"
new_name = st.text_input(
f"Name for {speaker.speaker_id}",
value=speaker.display_name,
key=new_name_key
)
if new_name != speaker.display_name:
if st.button(f"Save", key=f"save_rename_{speaker.speaker_id}_{transcription_id}_{context}"):
multi_speaker.update_speaker_name(transcription_id, speaker.speaker_id, new_name)
st.success(f"Renamed to {new_name}")
st.rerun()
st.markdown("---")
# Chat mode selection
mode_key = f"chat_mode_{transcription_id}_{context}"
chat_mode = st.radio(
"Chat Mode",
["🎤 Individual Speaker", "👥 Panel Discussion"],
key=mode_key,
horizontal=True
)
if chat_mode == "🎤 Individual Speaker":
render_individual_speaker_chat(multi_speaker, speakers, transcription_id, context)
else:
render_panel_discussion_chat(multi_speaker, speakers, transcription_id, context)
def render_individual_speaker_chat(multi_speaker: 'MultiSpeakerPersona', speakers: dict, transcription_id: int, context: str):
"""Chat with a single speaker."""
speaker_list = list(speakers.values())
speaker_names = [s.display_name for s in speaker_list]
# Speaker selection
selected_idx = st.selectbox(
"Select Speaker to Chat With",
range(len(speaker_names)),
format_func=lambda x: speaker_names[x],
key=f"speaker_select_{transcription_id}_{context}"
)
selected_speaker = speaker_list[selected_idx]
# Show speaker info (using checkbox toggle to avoid nested expander)
show_speaker_info = st.checkbox(f"ℹ️ About {selected_speaker.display_name}", key=f"show_info_{selected_speaker.speaker_id}_{transcription_id}_{context}")
if show_speaker_info:
st.markdown(f"**Word Count:** {selected_speaker.word_count}")
st.markdown(f"**Segments:** {len(selected_speaker.transcript_segments)}")
if selected_speaker.topics:
st.markdown(f"**Topics:** {', '.join(selected_speaker.topics)}")
if selected_speaker.persona_prompt:
st.caption(selected_speaker.persona_prompt[:300] + "..." if len(selected_speaker.persona_prompt) > 300 else selected_speaker.persona_prompt)
# Chat interface
st.markdown(f"### 💬 Chat with {selected_speaker.display_name}")
messages_key = f"individual_chat_{selected_speaker.speaker_id}_{transcription_id}_{context}"
if messages_key not in st.session_state:
st.session_state[messages_key] = []
# Display chat history
for message in st.session_state[messages_key]:
with st.chat_message(message["role"]):
st.markdown(message["content"])
if "timestamp_refs" in message and message["timestamp_refs"]:
st.caption(f"Referenced: {', '.join([f'[{ts}]' for ts in message['timestamp_refs']])}")
# Chat input
chat_input_key = f"individual_input_{selected_speaker.speaker_id}_{transcription_id}_{context}"