-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
executable file
·1512 lines (1269 loc) · 57.9 KB
/
Copy pathapp.py
File metadata and controls
executable file
·1512 lines (1269 loc) · 57.9 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 threading
import logging
import os
import zipfile
import shutil
import pytz
import re
import requests
import time
import markdown
import bcrypt
import json
from datetime import datetime, timedelta
from functools import wraps
from werkzeug.utils import secure_filename
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify, session, send_file, Response
from sqlalchemy import func, case
from config import load_config, save_config
from database import init_db, db
from models import Campaign, Session, Job, Transcript, LLMLog, DiscordLog
from worker import JobManager
from io import BytesIO
from xhtml2pdf import pisa
from urllib.parse import urlparse, urljoin
from types import SimpleNamespace
# Configure Logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
app = Flask(__name__)
app_config = load_config()
app.secret_key = app_config.get('flask_secret_key', 'fallback_dev_key_if_config_fails')
APP_VERSION = '4.3.7'
def apply_transcript_options(text, campaign, session=None):
"""
Apply transcript processing options, with session-level overrides
taking precedence over campaign settings when set.
"""
if not text:
return text
# Resolve effective values: session override > campaign setting
if session is not None:
effective_map = session.effective_username_map()
remove_timestamps = session.effective_remove_timestamps()
consolidate_lines = session.effective_consolidate_lines()
else:
effective_map = campaign.username_map if campaign else None
remove_timestamps = campaign.transcript_remove_timestamps if campaign else False
consolidate_lines = campaign.transcript_consolidate_lines if campaign else False
# 1. Username renaming
if effective_map:
try:
umap = json.loads(effective_map)
for discord_name, display_name in umap.items():
if discord_name and display_name:
text = re.sub(
r'(?m)^(\[\d{2}:\d{2}:\d{2}\]\s*)?' + re.escape(discord_name) + r'(?=:)',
lambda m: (m.group(1) or '') + display_name,
text
)
except Exception:
pass
# 2. Remove timestamps
if remove_timestamps:
text = re.sub(r'^\[\d{2}:\d{2}:\d{2}\]\s*', '', text, flags=re.MULTILINE)
# 3. Consolidate consecutive lines by speaker
if consolidate_lines:
speaker_re = re.compile(r'^(?:\[\d{2}:\d{2}:\d{2}\]\s*)?([^:\n]+):\s*(.*)')
lines = text.split('\n')
consolidated = []
cur_speaker = None
cur_parts = []
for line in lines:
stripped = line.strip()
if not stripped:
if cur_speaker and cur_parts:
consolidated.append(f'{cur_speaker}: ' + ' '.join(cur_parts))
cur_speaker = None
cur_parts = []
consolidated.append('')
continue
m = speaker_re.match(stripped)
if m:
speaker, content = m.group(1).strip(), m.group(2).strip()
if speaker == cur_speaker:
if content:
cur_parts.append(content)
else:
if cur_speaker and cur_parts:
consolidated.append(f'{cur_speaker}: ' + ' '.join(cur_parts))
cur_speaker = speaker
cur_parts = [content] if content else []
else:
if cur_speaker and cur_parts:
consolidated.append(f'{cur_speaker}: ' + ' '.join(cur_parts))
cur_speaker = None
cur_parts = []
consolidated.append(line)
if cur_speaker and cur_parts:
consolidated.append(f'{cur_speaker}: ' + ' '.join(cur_parts))
text = '\n'.join(consolidated)
return text
@app.template_filter('from_json')
def from_json_filter(value):
"""Parse a JSON string in a Jinja template."""
try:
return json.loads(value) if value else {}
except Exception:
return {}
@app.context_processor
def inject_version():
hostname = os.environ.get('HOSTNAME', 'scribble')
container_name = hostname.capitalize()
return dict(app_version=APP_VERSION, container_name=container_name)
@app.route('/scribble.png')
def serve_logo():
return send_file('/app/scribble.png', mimetype='image/png')
# Initialize Database
init_db(app)
@app.context_processor
def utility_processor():
"""Inject smart path check into templates."""
# Build archive file set once per request for the listdir fallback
archive_dir = '/data/archive'
try:
archive_files = set(os.listdir(archive_dir)) if os.path.exists(archive_dir) else set()
except Exception:
archive_files = set()
def folder_exists_check(path, filename=None):
if os.path.exists(path):
return True
try:
session_name = os.path.basename(path.rstrip('/'))
if os.path.exists(os.path.join(archive_dir, session_name + ".flac.zip")): return True
if os.path.exists(os.path.join(archive_dir, session_name + ".zip")): return True
if filename:
if os.path.exists(os.path.join(archive_dir, filename)): return True
return any(f.endswith(filename) for f in archive_files)
except Exception:
return False
return False
return dict(folder_exists_check=folder_exists_check)
# --- AUTH DECORATOR ---
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get('logged_in'):
return redirect(url_for('login', next=request.url))
return f(*args, **kwargs)
return decorated_function
@app.context_processor
def inject_config():
return dict(
config=load_config(),
system_mode=os.environ.get('SCRIBBLE_MODE', 'standard')
)
# --- Update Checker Logic ---
LATEST_VERSION_CACHE = None
CHECK_INTERVAL = 3600 # Check once per hour
def _version_check_worker():
global LATEST_VERSION_CACHE
while True:
try:
url = 'https://raw.githubusercontent.com/goose-ws/scribble/refs/heads/main/app.py'
resp = requests.get(url, timeout=10)
if resp.status_code == 200:
match = re.search(r"APP_VERSION\s*=\s*['\"]([0-9.]+)['\"]", resp.text)
if match:
LATEST_VERSION_CACHE = match.group(1)
except Exception:
pass
time.sleep(CHECK_INTERVAL)
_version_thread = threading.Thread(target=_version_check_worker, daemon=True)
_version_thread.start()
@app.context_processor
def inject_update_status():
remote_ver = LATEST_VERSION_CACHE
is_update = bool(remote_ver and remote_ver != APP_VERSION)
return dict(update_available=is_update, latest_version=remote_ver)
def parse_llm_stats(summary_text):
stats = {}
if not summary_text:
return stats
patterns = {
'provider': r'🤖 LLM Provider: `(.*?)`',
'model': r'📋 Model: `(.*?)`',
'api_time': r'⌚ API time: `(.*?)`',
'tokens': r'🧾 Tokens: `(.*?)`'
}
for key, pattern in patterns.items():
match = re.search(pattern, summary_text)
if match:
val = match.group(1)
if key == 'tokens':
try:
val = re.sub(r'\d+', lambda m: "{:,}".format(int(m.group(0))), val)
except Exception:
pass
stats[key] = val
return stats
def parse_transcription_metrics(job_logs, transcripts):
metrics = {}
if not job_logs:
return metrics
start_pattern = r'\[(\d{2}:\d{2}:\d{2})\] Transcribing: .*? \(User: (.*?)\)'
end_pattern = r'\[(\d{2}:\d{2}:\d{2})\] - Completed (.*?)[:\.]'
starts = {}
for line in job_logs.split('\n'):
start_match = re.search(start_pattern, line)
if start_match:
time_str, username = start_match.groups()
starts[username] = datetime.strptime(time_str, '%H:%M:%S')
if username not in metrics:
metrics[username] = {'duration': '?', 'words': 0}
continue
end_match = re.search(end_pattern, line)
if end_match and starts:
current_user = list(starts.keys())[-1]
time_str = end_match.group(1)
end_time = datetime.strptime(time_str, '%H:%M:%S')
start_time = starts[current_user]
delta = end_time - start_time
if delta.total_seconds() < 0:
delta += timedelta(hours=24)
metrics[current_user]['duration'] = str(delta)
del starts[current_user]
for username, content in transcripts.items():
if username not in metrics:
metrics[username] = {'duration': 'N/A'}
metrics[username]['words'] = len(content.split())
return metrics
def parse_integrations_status(job_logs):
status = {
'discord_sent': False,
'scripts': []
}
if not job_logs:
return status
if "Sending to Discord... Sent." in job_logs:
status['discord_sent'] = True
script_pattern = r'(Finished|Failed): (.*?) \((.*?)\)'
for line in job_logs.split('\n'):
match = re.search(script_pattern, line)
if match:
state, name, outcome = match.groups()
status['scripts'].append({
'name': name,
'success': state == 'Finished',
'detail': outcome
})
return status
def get_campaign_stats():
"""Return per-campaign metrics dict: session count + per-user session appearances and word counts."""
all_campaigns = Campaign.query.all()
if not all_campaigns:
return all_campaigns, {}
# Single query for all sessions
all_sessions = Session.query.all()
sessions_by_campaign = {}
session_to_campaign = {}
for s in all_sessions:
sessions_by_campaign.setdefault(s.campaign_id, []).append(s)
session_to_campaign[s.id] = s.campaign_id
# Single query for all transcripts across all sessions
user_stats_by_campaign = {}
if session_to_campaign:
all_transcripts = Transcript.query.filter(
Transcript.session_id.in_(session_to_campaign.keys())
).all()
for t in all_transcripts:
camp_id = session_to_campaign[t.session_id]
uname = t.username or "Unknown"
camp_map = user_stats_by_campaign.setdefault(camp_id, {})
if uname not in camp_map:
camp_map[uname] = {"sessions": set(), "words": 0}
camp_map[uname]["sessions"].add(t.session_id)
if t.content:
camp_map[uname]["words"] += len(t.content.split())
# Assemble final structure
campaign_stats = {}
for campaign in all_campaigns:
user_stats_map = user_stats_by_campaign.get(campaign.id, {})
sorted_users = sorted(
[{"username": u, "session_count": len(v["sessions"]), "word_count": v["words"]}
for u, v in user_stats_map.items()],
key=lambda x: x["word_count"],
reverse=True
)
campaign_stats[campaign.id] = {
"campaign": campaign,
"session_count": len(sessions_by_campaign.get(campaign.id, [])),
"user_stats": sorted_users,
}
return all_campaigns, campaign_stats
# --- LOGIN ROUTES ---
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
password = request.form.get('password')
config = load_config()
stored = config.get('webui_password', '')
if stored.startswith('$2b$') or stored.startswith('$2a$'):
# Hashed — use bcrypt
password_valid = bcrypt.checkpw(password.encode(), stored.encode())
else:
# Plaintext (legacy) — compare directly, then migrate
password_valid = (password == stored)
if password_valid:
config['webui_password'] = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
save_config(config)
if password_valid:
session['logged_in'] = True
flash('Logged in successfully.', 'success')
def is_safe_url(target):
ref_url = urlparse(request.host_url)
test_url = urlparse(urljoin(request.host_url, target))
return test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc
next_page = request.args.get('next')
if not next_page or not is_safe_url(next_page):
next_page = url_for('dashboard')
return redirect(next_page)
else:
flash('Invalid password.', 'error')
return render_template('login.html')
@app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('Logged out.', 'info')
return redirect(url_for('login'))
# --- PROTECTED ROUTES ---
@app.route('/')
@login_required
def dashboard():
recent_sessions = Session.query.order_by(Session.created_at.desc()).limit(10).all()
all_campaigns, campaign_stats = get_campaign_stats()
return render_template('dashboard.html', sessions=recent_sessions,
campaigns=all_campaigns, campaign_stats=campaign_stats)
@app.route('/settings', methods=['GET', 'POST'])
@login_required
def settings():
config = load_config()
if request.method == 'POST':
for key, value in request.form.items():
if key in config:
if isinstance(config[key], bool):
config[key] = True if value == 'on' else False
elif isinstance(config[key], int):
try: config[key] = int(value)
except: pass
elif isinstance(config[key], float):
try: config[key] = float(value)
except: pass
else:
config[key] = value
new_password = request.form.get('webui_password', '').strip()
if new_password:
config['webui_password'] = bcrypt.hashpw(new_password.encode(), bcrypt.gensalt()).decode()
config['archive_zip'] = 'archive_zip' in request.form
config['db_space_saver'] = 'db_space_saver' in request.form
config['dark_mode'] = 'dark_mode' in request.form
# Handle per-provider token costs
llm_costs = config.get('llm_costs', {})
for provider, key in [('Google', 'google'), ('OpenAI', 'openai'), ('Anthropic', 'anthropic'), ('Ollama', 'ollama')]:
input_val = request.form.get(f'llm_cost_{key}_input')
output_val = request.form.get(f'llm_cost_{key}_output')
if provider not in llm_costs:
llm_costs[provider] = {}
if input_val is not None:
try: llm_costs[provider]['input'] = float(input_val)
except (ValueError, TypeError): pass
if output_val is not None:
try: llm_costs[provider]['output'] = float(output_val)
except (ValueError, TypeError): pass
config['llm_costs'] = llm_costs
save_config(config)
flash('Settings saved successfully!', 'success')
return redirect(url_for('settings'))
return render_template('settings.html', config=config)
@app.route('/settings/toggle_dark_mode', methods=['POST'])
@login_required
def toggle_dark_mode():
config = load_config()
config['dark_mode'] = not config.get('dark_mode', False)
save_config(config)
return redirect(request.referrer or url_for('dashboard'))
@app.route('/campaigns', methods=['GET', 'POST'])
@login_required
def campaigns():
scripts_dir = '/data/scripts'
if not os.path.exists(scripts_dir):
os.makedirs(scripts_dir)
available_scripts = [f for f in os.listdir(scripts_dir)
if os.path.isfile(os.path.join(scripts_dir, f))]
if request.method == 'POST':
name = request.form.get('name')
if not name:
flash('Campaign Name is required.', 'error')
return redirect(url_for('campaigns'))
selected_scripts = request.form.getlist('scripts')
script_paths_str = ",".join(selected_scripts)
# Handle LLM overrides
llm_prov = request.form.get('llm_provider') or None
llm_mod = request.form.get('llm_model')
if not llm_mod: llm_mod = None
def _nstr(val): return val.strip() if val and val.strip() else None
def _nint(val):
try: return int(val) if val and val.strip() else None
except (ValueError, TypeError): return None
def _nfloat(val):
try: return float(val) if val and val.strip() else None
except (ValueError, TypeError): return None
new_campaign = Campaign(
name=name,
discord_webhook=request.form.get('discord_webhook'),
system_prompt=request.form.get('system_prompt'),
script_paths=script_paths_str,
recap_context_enabled='recap_context_enabled' in request.form,
recap_context_count=int(request.form.get('recap_context_count') or 3),
llm_provider=llm_prov,
llm_model=llm_mod,
llm_input_cost=_nfloat(request.form.get('llm_input_cost')),
llm_output_cost=_nfloat(request.form.get('llm_output_cost')),
whisper_model=_nstr(request.form.get('whisper_model')),
whisper_threads=_nint(request.form.get('whisper_threads')),
whisper_batch_size=_nint(request.form.get('whisper_batch_size')),
whisper_beam_size=_nint(request.form.get('whisper_beam_size')),
whisper_compute_type=_nstr(request.form.get('whisper_compute_type')),
whisper_language=_nstr(request.form.get('whisper_language')),
whisper_initial_prompt=_nstr(request.form.get('whisper_initial_prompt')),
vad_method=_nstr(request.form.get('vad_method')),
vad_onset=_nfloat(request.form.get('vad_onset')),
vad_offset=_nfloat(request.form.get('vad_offset')),
)
try:
db.session.add(new_campaign)
db.session.commit()
flash(f'Campaign "{name}" created!', 'success')
except Exception as e:
db.session.rollback()
flash(f'Error creating campaign: {e}', 'error')
return redirect(url_for('campaigns'))
all_campaigns, campaign_stats = get_campaign_stats()
return render_template('campaigns.html',
campaigns=all_campaigns,
available_scripts=available_scripts,
campaign_stats=campaign_stats)
@app.route('/campaigns/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def edit_campaign(id):
campaign = Campaign.query.get_or_404(id)
scripts_dir = '/data/scripts'
if not os.path.exists(scripts_dir):
os.makedirs(scripts_dir)
available_scripts = [f for f in os.listdir(scripts_dir)
if os.path.isfile(os.path.join(scripts_dir, f))]
current_scripts = campaign.script_paths.split(',') if campaign.script_paths else []
if request.method == 'POST':
campaign.name = request.form.get('name')
campaign.discord_webhook = request.form.get('discord_webhook')
campaign.system_prompt = request.form.get('system_prompt')
selected_scripts = request.form.getlist('scripts')
campaign.script_paths = ",".join(selected_scripts)
campaign.recap_context_enabled = 'recap_context_enabled' in request.form
campaign.recap_context_count = int(request.form.get('recap_context_count') or 3)
# Handle LLM overrides
llm_prov = request.form.get('llm_provider')
campaign.llm_provider = llm_prov or None
llm_mod = request.form.get('llm_model')
campaign.llm_model = llm_mod if llm_mod else None
def _nstr(val): return val.strip() if val and val.strip() else None
def _nint(val):
try: return int(val) if val and val.strip() else None
except (ValueError, TypeError): return None
def _nfloat(val):
try: return float(val) if val and val.strip() else None
except (ValueError, TypeError): return None
campaign.llm_input_cost = _nfloat(request.form.get('llm_input_cost'))
campaign.llm_output_cost = _nfloat(request.form.get('llm_output_cost'))
campaign.whisper_model = _nstr(request.form.get('whisper_model'))
campaign.whisper_threads = _nint(request.form.get('whisper_threads'))
campaign.whisper_batch_size = _nint(request.form.get('whisper_batch_size'))
campaign.whisper_beam_size = _nint(request.form.get('whisper_beam_size'))
campaign.whisper_compute_type = _nstr(request.form.get('whisper_compute_type'))
campaign.whisper_language = _nstr(request.form.get('whisper_language'))
campaign.whisper_initial_prompt = _nstr(request.form.get('whisper_initial_prompt'))
cond = request.form.get('whisper_condition_on_previous_text')
if cond == 'true':
campaign.whisper_condition_on_previous_text = True
elif cond == 'false':
campaign.whisper_condition_on_previous_text = False
else:
campaign.whisper_condition_on_previous_text = None
campaign.whisper_compression_ratio_threshold = _nfloat(request.form.get('whisper_compression_ratio_threshold'))
campaign.whisper_no_speech_threshold = _nfloat(request.form.get('whisper_no_speech_threshold'))
campaign.vad_min_silence_ms = _nfloat(request.form.get('vad_min_silence_ms'))
campaign.vad_max_speech_s = _nfloat(request.form.get('vad_max_speech_s'))
campaign.vad_method = _nstr(request.form.get('vad_method'))
campaign.vad_onset = _nfloat(request.form.get('vad_onset'))
campaign.vad_offset = _nfloat(request.form.get('vad_offset'))
# Transcript processing options
discord_names = request.form.getlist('umap_discord')
display_names = request.form.getlist('umap_display')
umap = {d.strip(): n.strip() for d, n in zip(discord_names, display_names) if d.strip()}
campaign.username_map = json.dumps(umap) if umap else None
campaign.transcript_remove_timestamps = 'transcript_remove_timestamps' in request.form
campaign.transcript_consolidate_lines = 'transcript_consolidate_lines' in request.form
should_be_default = 'is_default' in request.form
if should_be_default:
Campaign.query.filter(Campaign.id != campaign.id).update({Campaign.is_default: False})
campaign.is_default = True
else:
campaign.is_default = False
try:
db.session.commit()
flash(f'Campaign "{campaign.name}" updated!', 'success')
return redirect(url_for('campaigns'))
except Exception as e:
db.session.rollback()
flash(f'Error updating campaign: {e}', 'error')
return render_template('edit_campaign.html',
campaign=campaign,
available_scripts=available_scripts,
current_scripts=current_scripts)
@app.route('/campaigns/set_default/<int:campaign_id>', methods=['POST'])
@login_required
def set_default_campaign(campaign_id):
Campaign.query.update({Campaign.is_default: False})
camp = Campaign.query.get_or_404(campaign_id)
camp.is_default = True
db.session.commit()
flash(f'"{camp.name}" is now the default campaign.', 'success')
return redirect(url_for('campaigns'))
@app.route('/campaigns/delete/<int:id>', methods=['POST'])
@login_required
def delete_campaign(id):
campaign = Campaign.query.get_or_404(id)
try:
db.session.delete(campaign)
db.session.commit()
flash(f'Campaign "{campaign.name}" deleted.', 'info')
except Exception as e:
flash(f'Error deleting campaign: {e}', 'error')
return redirect(url_for('campaigns'))
# --- UPLOAD & PROCESSING LOGIC ---
def parse_session_date(info_path):
utc_date = datetime.utcnow()
try:
with open(info_path, 'r') as f:
for line in f:
if "Start time:" in line:
time_str = line.split("Start time:", 1)[1].strip()
time_str = time_str.replace('Z', '+00:00')
utc_date = datetime.fromisoformat(time_str)
break
except Exception as e:
logging.error(f"Error parsing info.txt: {e}")
return utc_date, "Unknown Date"
target_tz = os.environ.get('TZ', 'UTC')
try:
local_tz = pytz.timezone(target_tz)
local_date = utc_date.astimezone(local_tz)
return utc_date, local_date.strftime('%Y-%m-%d %H:%M:%S')
except Exception as e:
logging.error(f"Timezone conversion error: {e}")
return utc_date, str(utc_date)
@app.route('/campaigns/<int:campaign_id>')
@login_required
def campaign_detail(campaign_id):
campaign = Campaign.query.get_or_404(campaign_id)
sessions = Session.query.filter_by(campaign_id=campaign.id).order_by(Session.session_number.desc(), Session.created_at.desc()).all()
total_words = 0
total_in = 0
total_out = 0
total_combined = 0
total_cost = 0.0
discord_count = 0
discord_errors = 0
session_ids = [s.id for s in sessions]
if session_ids:
logs = DiscordLog.query.filter(DiscordLog.session_id.in_(session_ids)).all()
discord_count = len(logs)
discord_errors = sum(1 for log in logs if log.http_status not in [200, 201, 204])
for s in sessions:
if s.transcript_text:
total_words += len(s.transcript_text.split())
stats = parse_llm_stats(s.summary_text)
token_str = stats.get('tokens', '')
if token_str:
match = re.search(r'([\d,]+)\s+in\s*\|\s*([\d,]+)\s+out\s*\|\s*([\d,]+)\s+total', token_str)
if match:
try:
in_tok = int(match.group(1).replace(',', ''))
out_tok = int(match.group(2).replace(',', ''))
total_in += in_tok
total_out += out_tok
total_combined += int(match.group(3).replace(',', ''))
from config import get_effective_config
app_config = load_config()
eff = get_effective_config(app_config, s.campaign)
total_cost += (in_tok * eff.get('llm_input_cost', 0.0) / 1_000_000 +
out_tok * eff.get('llm_output_cost', 0.0) / 1_000_000)
except Exception:
pass
return render_template('campaign_detail.html',
campaign=campaign,
sessions=sessions,
total_words="{:,}".format(total_words),
total_in="{:,}".format(total_in),
total_out="{:,}".format(total_out),
total_combined="{:,}".format(total_combined),
total_cost="{:,.4f}".format(total_cost),
discord_count=discord_count,
discord_errors=discord_errors)
@app.route('/campaigns/<int:campaign_id>/download_pdf/<doc_type>')
@login_required
def download_campaign_pdf(campaign_id, doc_type):
campaign = Campaign.query.get_or_404(campaign_id)
sessions = Session.query.filter_by(campaign_id=campaign.id).order_by(Session.session_number.asc()).all()
html_content = f"""
<html>
<head>
<style>
@page {{ size: A4; margin: 2cm; }}
body {{ font-family: Helvetica, sans-serif; font-size: 10pt; line-height: 1.4; }}
h1 {{ color: #2c3e50; text-align: center; font-size: 24pt; margin-bottom: 20px; }}
h2 {{ color: #2980b9; border-bottom: 1px solid #eee; padding-bottom: 10px; margin-top: 30px; page-break-after: avoid; }}
.meta {{ color: #95a5a6; font-size: 9pt; font-style: italic; margin-bottom: 10px; }}
.toc-entry {{ margin-bottom: 5px; font-size: 11pt; }}
.toc-entry a {{ text-decoration: none; color: #2c3e50; }}
.page-break {{ page-break-before: always; }}
.dialogue-line {{ margin-bottom: 8px; text-align: left; }}
.speaker {{ font-weight: bold; color: #444; }}
.recap-content {{ text-align: justify; }}
</style>
</head>
<body>
"""
title_text = "Campaign Recap" if doc_type == 'recap' else "Campaign Transcripts"
html_content += f"""
<div style="text-align: center; margin-top: 200px;">
<h1>{campaign.name}</h1>
<h2>{title_text}</h2>
<p>Generated on {datetime.now().strftime('%Y-%m-%d')}</p>
</div>
<div class="page-break"></div>
"""
html_content += "<h1>Table of Contents</h1>"
for s in sessions:
if doc_type == 'recap' and not s.summary_text: continue
if doc_type == 'transcript' and not s.transcript_text: continue
entry_title = f"Session {s.session_number}: {s.session_date.strftime('%Y-%m-%d')}"
html_content += f"""
<div class='toc-entry'>
<a href='#session_{s.id}'>{entry_title}</a>
</div>
"""
html_content += "<div class='page-break'></div>"
for s in sessions:
date_str = s.session_date.strftime('%B %d, %Y')
anchor = f'<a name="session_{s.id}"></a>'
if doc_type == 'recap':
if not s.summary_text: continue
lines = s.summary_text.split('\n')
header_ended = False
content_lines = []
for line in lines:
if '##' in line and not header_ended: header_ended = True
if header_ended: content_lines.append(line)
elif not any(c in line for c in ['🤖', '📋', '⌚', '🧾']):
content_lines.append(line)
md_text = "\n".join(content_lines)
body_html = markdown.markdown(md_text)
html_content += f"""
{anchor}
<h2>Session {s.session_number}</h2>
<div class="meta">{date_str}</div>
<div class="recap-content">{body_html}</div>
<div class="page-break"></div>
"""
elif doc_type == 'transcript':
if not s.transcript_text: continue
html_content += f"""
{anchor}
<h2>Session {s.session_number}</h2>
<div class="meta">{date_str}</div>
<div class="transcript-content">
"""
raw_lines = s.transcript_text.split('\n')
for line in raw_lines:
line = line.strip()
if not line: continue
safe_line = line.replace('<', '<').replace('>', '>')
bracket_idx = safe_line.find(']')
sep_idx = safe_line.find(':', bracket_idx) if bracket_idx != -1 else -1
if bracket_idx != -1 and sep_idx != -1:
formatted_line = f"<span class='speaker'>{safe_line[:sep_idx+1]}</span>{safe_line[sep_idx+1:]}"
else:
formatted_line = safe_line
html_content += f"<div class='dialogue-line'>{formatted_line}</div>"
html_content += "</div><div class='page-break'></div>"
html_content += "</body></html>"
pdf_output = BytesIO()
pisa_status = pisa.CreatePDF(html_content, dest=pdf_output)
if pisa_status.err:
return f"Error generating PDF: {pisa_status.err}", 500
pdf_output.seek(0)
filename = f"{campaign.name.replace(' ', '_')}_{doc_type}.pdf"
return Response(
pdf_output,
mimetype='application/pdf',
headers={"Content-disposition": f"attachment; filename={filename}"}
)
def renumber_campaign_sessions(campaign_id):
"""Recompute session_number for every session in a campaign.
Unknown-date sessions → 0. Dated sessions → 1, 2, 3 … in ascending date order.
Multiple unknown-date sessions all receive 0."""
sessions = Session.query.filter_by(campaign_id=campaign_id).all()
unknown = [s for s in sessions if s.local_time_str == 'Unknown Date']
dated = sorted([s for s in sessions if s.local_time_str != 'Unknown Date'],
key=lambda s: s.session_date)
for s in unknown:
s.session_number = 0
for i, s in enumerate(dated, start=1):
s.session_number = i
db.session.commit()
@app.route('/upload', methods=['GET', 'POST'])
@login_required
def upload():
if request.method == 'GET':
campaigns = Campaign.query.all()
default_campaign_id = next((c.id for c in campaigns if c.is_default), None)
return render_template('upload.html',
campaigns=campaigns,
default_campaign_id=default_campaign_id)
if 'file' not in request.files:
return jsonify({'error': 'No file part'}), 400
file = request.files['file']
campaign_id = request.form.get('campaign_id')
if file.filename == '':
return jsonify({'error': 'No selected file'}), 400
if not campaign_id:
return jsonify({'error': 'No campaign selected'}), 400
if file:
filename = secure_filename(file.filename)
upload_id = datetime.now().strftime('%Y%m%d_%H%M%S')
upload_dir = os.path.join('/data/input', upload_id)
os.makedirs(upload_dir, exist_ok=True)
file_path = os.path.join(upload_dir, filename)
try:
file.save(file_path)
is_flac = filename.lower().endswith('.flac')
if is_flac:
now_utc = datetime.utcnow()
info_path = os.path.join(upload_dir, 'info.txt')
with open(info_path, 'w') as f:
f.write(f"Start time: {now_utc.strftime('%Y-%m-%dT%H:%M:%S')}+00:00\n")
session_date_utc, local_time_str = parse_session_date(info_path)
else:
if not zipfile.is_zipfile(file_path): raise Exception("Not a zip.")
with zipfile.ZipFile(file_path, 'r') as z: z.extractall(upload_dir)
info_path = os.path.join(upload_dir, 'info.txt')
session_date_utc, local_time_str = parse_session_date(info_path)
# Override date if the user supplied one on the upload form
manual_date_raw = request.form.get('session_date', '').strip()
if manual_date_raw:
try:
naive_dt = datetime.strptime(manual_date_raw, '%Y-%m-%dT%H:%M')
target_tz = os.environ.get('TZ', 'UTC')
try:
local_tz = pytz.timezone(target_tz)
local_dt = local_tz.localize(naive_dt)
session_date_utc = local_dt.astimezone(pytz.utc).replace(tzinfo=None)
except Exception:
session_date_utc = naive_dt
local_time_str = naive_dt.strftime('%Y-%m-%d %H:%M:%S')
except ValueError:
pass
new_session = Session(
campaign_id=campaign_id,
session_number=0,
session_date=session_date_utc,
local_time_str=local_time_str,
original_filename=filename,
directory_path=upload_dir,
status="Processing"
)
db.session.add(new_session)
db.session.commit()
renumber_campaign_sessions(campaign_id)
initial_job = Job(session_id=new_session.id, step="transcribe", status="pending", logs="Job queued.")
db.session.add(initial_job)
db.session.commit()
return jsonify({'success': True, 'redirect': url_for('dashboard')})
except Exception as e:
logging.error(f"Upload failed: {e}")
if os.path.exists(upload_dir): shutil.rmtree(upload_dir)
return jsonify({'error': str(e)}), 500
@app.route('/session/<int:session_id>/save_settings', methods=['POST'])
@login_required
def save_session_settings(session_id):
session_obj = Session.query.get_or_404(session_id)
campaign = session_obj.campaign
# --- System Prompt ---
submitted_prompt = request.form.get('session_prompt', '').strip()
if not submitted_prompt or submitted_prompt == (campaign.system_prompt or '').strip():
session_obj.session_prompt = None # identical to campaign → inherit
else:
session_obj.session_prompt = submitted_prompt
# --- Username Map (built from umap_discord / umap_display row pairs) ---
discord_names = request.form.getlist('umap_discord')
display_names = request.form.getlist('umap_display')
umap = {d.strip(): v.strip() for d, v in zip(discord_names, display_names)
if d.strip() and v.strip()}
if umap:
submitted_map = json.dumps(umap, ensure_ascii=False)
# If identical to the campaign map, treat as inherit
try:
campaign_map = json.loads(campaign.username_map) if campaign.username_map else {}
except Exception:
campaign_map = {}
session_obj.session_username_map = None if umap == campaign_map else submitted_map
else:
session_obj.session_username_map = None
# --- Tri-state selects (inherit / on / off) ---
for field in ('session_remove_timestamps', 'session_consolidate_lines'):
val = request.form.get(field, 'inherit')
if val == 'on':
setattr(session_obj, field, True)
elif val == 'off':
setattr(session_obj, field, False)
else:
setattr(session_obj, field, None)
db.session.commit()
flash('Session settings saved.', 'success')
return redirect(url_for('session_detail', session_id=session_id))
@app.route('/session/<int:session_id>/update_date', methods=['POST'])
@login_required
def update_session_date(session_id):
session_obj = Session.query.get_or_404(session_id)
try:
raw = request.form.get('session_date', '').strip()
# Accept "YYYY-MM-DDThh:mm" from datetime-local input
naive_dt = datetime.strptime(raw, '%Y-%m-%dT%H:%M')
target_tz = os.environ.get('TZ', 'UTC')
try:
local_tz = pytz.timezone(target_tz)
local_dt = local_tz.localize(naive_dt)
utc_dt = local_dt.astimezone(pytz.utc).replace(tzinfo=None)
display_str = naive_dt.strftime('%Y-%m-%d %H:%M:%S')