-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathapp.py
More file actions
4058 lines (3433 loc) · 161 KB
/
app.py
File metadata and controls
4058 lines (3433 loc) · 161 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
"""
Doza Assist
A local interview transcription, client review, and FCPX editing tool.
Built for Doza Visuals.
"""
import os
import json
import uuid
import time
import shutil
import subprocess
import threading
import hashlib
import re as _re
from datetime import datetime
from pathlib import Path
from flask import Flask, render_template, request, jsonify, send_file, redirect, url_for, Response, stream_with_context
from werkzeug.utils import secure_filename
from exporters import get_exporter, PLATFORMS, DEFAULT_PLATFORM
from exporters.media_probe import (
get_video_resolution, get_video_framerate, get_video_start_timecode_frames,
)
from doza_assist.fcpxml import (
parse_fcpxml, ParseError, Select, WriterError,
write_selects_as_new_project, write_markers_on_timeline,
)
from doza_assist.fcpxml.timeline_audio import (
render_timeline_audio, TimelineAudioError,
)
import preferences as prefs
# Hoisted from the global errorhandler to fail loud at server start if the
# ``ai_providers`` package is missing from the bundle, instead of starting
# Flask and then having every 500 response mask the real error with a
# secondary ``ModuleNotFoundError`` from the lazy import (see issue #25).
from ai_providers import ProviderError
def get_project_platform(project: dict) -> str:
"""Return the project's editing platform, falling back to the global default."""
p = (project or {}).get('editing_platform')
if p in PLATFORMS:
return p
return prefs.get_default_platform()
def _exporter_response(result, project, exporter):
"""Send an export file with X-Export-* headers for the frontend toast."""
response = send_file(
result.file_path,
as_attachment=True,
download_name=result.filename,
)
response.headers['X-Export-Format'] = result.format_name
response.headers['X-Export-Platform'] = result.platform_name
response.headers['X-Export-Extension'] = exporter.file_extension
if result.warnings:
# Headers must be ASCII-safe; join with " | ".
response.headers['X-Export-Warnings'] = ' | '.join(result.warnings)
return response
app = Flask(__name__)
# Data dir: honor DOZA_DATA_DIR if set (the packaged .app launcher points this
# at ~/Library/Application Support/DozaAssist). Fall back to the source tree
# for `python3 app.py` dev runs. Must never default to a path inside a signed
# .app bundle — those are read-only and os.makedirs below would EPERM.
_data_dir = os.environ.get('DOZA_DATA_DIR') or os.path.dirname(__file__)
app.config['PROJECTS_DIR'] = os.path.join(_data_dir, 'projects')
app.config['EXPORTS_DIR'] = os.path.join(_data_dir, 'exports')
# Small file drag-and-drop limit (500MB)
app.config['MAX_CONTENT_LENGTH'] = 32 * 1024 * 1024 * 1024 # 32 GB — My Style imports multiple large masters
ALLOWED_EXTENSIONS = {'wav', 'mp3', 'mp4', 'mov', 'aac', 'm4a', 'flac', 'aif', 'aiff', 'mxf', 'fcpxml'}
os.makedirs(app.config['PROJECTS_DIR'], exist_ok=True)
os.makedirs(app.config['EXPORTS_DIR'], exist_ok=True)
@app.context_processor
def inject_brand():
"""Make the user-visible app brand and logo configurable from the
launching shell.
Defaults: brand = "Doza Assist", logo_url = "/static/logo.jpg".
An external launcher (a downstream shell that bundles this Flask
backend) can override by setting DOZA_BRAND and/or DOZA_LOGO_URL in
the environment before spawning python -- the shell is responsible
for ensuring whatever URL it points at actually serves an image
(drop the logo into static/ before launch).
The version import is wrapped because a stale or wrong ``doza_assist``
package on sys.path (e.g. shadowed by an old pip install in the user's
venv) can make ``__version__`` unimportable even on a v3.5.3+ bundle —
and an ImportError here crashes every dashboard render, which leaves
Flask half-alive and the port stuck (issue #25). Reading the version
as "unknown" is a much better failure mode than the app refusing to
launch.
"""
try:
from doza_assist import __version__ as _doza_version
except (ImportError, AttributeError) as e:
print(
f"WARNING: could not read doza_assist.__version__ ({type(e).__name__}: {e}). "
"App will render with version='unknown'. This usually means a stale or "
"shadowed doza_assist package on sys.path — check the venv at "
"~/Library/Application Support/DozaAssist/venv for an old install.",
flush=True,
)
_doza_version = 'unknown'
return {
'brand': os.environ.get('DOZA_BRAND', 'Doza Assist'),
'logo_url': os.environ.get('DOZA_LOGO_URL', '/static/logo.jpg'),
'app_version': _doza_version,
}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def _resolve_fcpxml_path(source_path: str) -> str:
"""Given either a .fcpxml file or a .fcpxmld bundle directory, return the
path to the actual FCPXML document inside.
FCP exports the bundle form by default (a directory with Info.fcpxml inside);
editors who "Export XML" can get either form depending on FCP's dialog.
"""
if os.path.isdir(source_path) and source_path.rstrip('/').endswith('.fcpxmld'):
inner = os.path.join(source_path, 'Info.fcpxml')
if not os.path.isfile(inner):
raise ValueError(f'FCPXML bundle missing Info.fcpxml: {source_path}')
return inner
return source_path
def _is_fcpxml_input(path: str) -> bool:
lower = path.lower().rstrip('/')
return lower.endswith('.fcpxml') or lower.endswith('.fcpxmld')
def _ingest_fcpxml(fcpxml_path: str, project_dir: str) -> dict:
"""Parse an FCPXML, verify its audio source(s) are on disk, and return a
dict of fields to merge into the project's meta.json.
For single-source spines, the project's ``audio_path`` is the referenced
source file directly. For multi-source spines (mixed mc-clip/sync-clip or
multiple distinct audio assets), a composed timeline WAV is rendered into
the project directory and used as ``audio_path`` — transcription then
produces timestamps aligned to the sequence timeline.
Raises :class:`ValueError` with an editor-friendly message if any audio
source cannot be located — typically because the edit drive is not mounted.
"""
inner_path = _resolve_fcpxml_path(fcpxml_path)
try:
parsed = parse_fcpxml(inner_path)
except ParseError as e:
raise ValueError(f'Could not read FCPXML: {e}') from e
# Check every referenced source, not just the representative one — a
# multi-source spine can reference several drives.
unique_paths = []
seen = set()
for seg in parsed.spine_segments:
if seg.audio_source is None:
continue
p = seg.audio_source.path
if p in seen:
continue
seen.add(p)
unique_paths.append(p)
for p in unique_paths:
if not os.path.exists(p):
vol = ''
if p.startswith('/Volumes/'):
parts = p.split('/', 3)
vol = parts[2] if len(parts) > 2 else ''
hint = f' Is the "{vol}" drive mounted?' if vol else ''
raise ValueError(
f'FCPXML parsed OK, but the audio file it references was not found: '
f'{p}.{hint}'
)
# Stash the original FCPXML inside the project directory so the writer
# module can round-trip selects back out without needing the user to still
# have the source file accessible.
os.makedirs(project_dir, exist_ok=True)
fcpxml_copy_name = os.path.basename(inner_path) or 'source.fcpxml'
fcpxml_copy_path = os.path.join(project_dir, fcpxml_copy_name)
if os.path.abspath(inner_path) != os.path.abspath(fcpxml_copy_path):
shutil.copy2(inner_path, fcpxml_copy_path)
if parsed.is_multi_source:
# Compose the sequence's dialogue into one timeline-space WAV so the
# transcription pipeline (which takes one audio file) produces
# timeline-relative timestamps end-to-end.
timeline_wav = os.path.join(project_dir, 'timeline_audio.wav')
try:
render_timeline_audio(parsed, timeline_wav)
except TimelineAudioError as e:
raise ValueError(f'Could not render timeline audio from FCPXML: {e}') from e
audio_path = timeline_wav
else:
audio_path = parsed.audio_file_path
return {
'audio_path': audio_path,
'fcpxml_source': {
**parsed.to_metadata_dict(),
'original_fcpxml_path': inner_path,
'stored_fcpxml_path': fcpxml_copy_path,
'timeline_audio_rendered': parsed.is_multi_source,
},
}
def get_project(project_id):
"""Load a project's metadata."""
project_dir = os.path.join(app.config['PROJECTS_DIR'], project_id)
meta_path = os.path.join(project_dir, 'meta.json')
if not os.path.exists(meta_path):
return None
with open(meta_path, 'r') as f:
return json.load(f)
def load_segment_vectors(project_id):
"""Load structured segment vectors for a project, or [] if not yet generated."""
path = os.path.join(app.config['PROJECTS_DIR'], project_id, 'segment_vectors.json')
if not os.path.exists(path):
return []
try:
with open(path, 'r') as f:
data = json.load(f)
return data if isinstance(data, list) else []
except (json.JSONDecodeError, OSError):
return []
def _paragraph_index_path(project_id):
return os.path.join(app.config['PROJECTS_DIR'], project_id, 'paragraph_index.json')
def load_paragraph_index(project_id):
"""Load the TF-IDF paragraph retrieval index for a project, or None if
not yet generated. Used by /chat to rank relevance via cosine similarity
in addition to literal keyword matching.
"""
from doza_assist.retrieval import load_index
return load_index(_paragraph_index_path(project_id))
def save_project(project_id, data):
"""Save a project's metadata."""
project_dir = os.path.join(app.config['PROJECTS_DIR'], project_id)
os.makedirs(project_dir, exist_ok=True)
with open(os.path.join(project_dir, 'meta.json'), 'w') as f:
json.dump(data, f, indent=2)
def list_projects():
"""List all projects sorted by date."""
projects = []
projects_dir = app.config['PROJECTS_DIR']
if not os.path.exists(projects_dir):
return projects
for pid in os.listdir(projects_dir):
meta_path = os.path.join(projects_dir, pid, 'meta.json')
if os.path.exists(meta_path):
with open(meta_path, 'r') as f:
meta = json.load(f)
meta['id'] = pid
projects.append(meta)
projects.sort(key=lambda x: x.get('created_at', ''), reverse=True)
return projects
def check_source_file(project):
"""Check if the source file still exists and is accessible."""
filepath = project.get('source_path', project.get('filepath', ''))
if not filepath:
return False, 'No source file path recorded'
if not os.path.exists(filepath):
return False, f'Source file not found: {filepath}'
return True, filepath
def format_file_size(size_bytes):
"""Format bytes into a human-readable string."""
if size_bytes < 1024:
return f"{size_bytes} B"
elif size_bytes < 1024 * 1024:
return f"{size_bytes / 1024:.1f} KB"
elif size_bytes < 1024 * 1024 * 1024:
return f"{size_bytes / (1024 * 1024):.1f} MB"
else:
return f"{size_bytes / (1024 * 1024 * 1024):.2f} GB"
# ── Activity log ─────────────────────────────────────────────────────────
def _activity_path(project_id):
return os.path.join(app.config['PROJECTS_DIR'], project_id, 'activity.json')
def log_activity(project_id, event_type, description):
"""Append an event to the project's activity log (newest first, capped at 50)."""
path = _activity_path(project_id)
entries = []
if os.path.exists(path):
try:
with open(path, 'r') as f:
entries = json.load(f)
except (json.JSONDecodeError, OSError):
entries = []
entries.insert(0, {
'ts': int(time.time()),
'type': event_type,
'description': description,
})
entries = entries[:50]
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w') as f:
json.dump(entries, f, indent=2)
except OSError:
pass
def get_recent_activity(project_id, limit=6):
"""Return the most recent activity entries with a pre-formatted relative timestamp."""
path = _activity_path(project_id)
if not os.path.exists(path):
return []
try:
with open(path, 'r') as f:
entries = json.load(f)
except (json.JSONDecodeError, OSError):
return []
now = int(time.time())
out = []
for e in entries[:limit]:
out.append({**e, 'relative': _relative_time(now - int(e.get('ts', now)))})
return out
def _relative_time(seconds):
if seconds < 60:
return 'just now'
if seconds < 3600:
return f'{seconds // 60}m ago'
if seconds < 86400:
return f'{seconds // 3600}h ago'
return f'{seconds // 86400}d ago'
# ── Routes ──────────────────────────────────────────────────────────────
@app.route('/')
def dashboard():
"""Main dashboard showing all projects grouped by folder."""
projects = list_projects()
# Group projects by folder
folders = {}
unfiled = []
for p in projects:
folder = p.get('folder', '')
if folder:
folders.setdefault(folder, []).append(p)
else:
unfiled.append(p)
# Sort folder names
sorted_folders = sorted(folders.items(), key=lambda x: x[0].lower())
return render_template('dashboard.html',
projects=projects,
folders=sorted_folders,
unfiled=unfiled)
@app.route('/folder/create', methods=['POST'])
def create_folder():
"""Create a folder (just a name — projects reference it)."""
name = (request.json or {}).get('name', '').strip()
if not name:
return jsonify({'error': 'Folder name required'}), 400
return jsonify({'status': 'created', 'name': name})
@app.route('/project/<project_id>/move', methods=['POST'])
def move_project(project_id):
"""Move a project to a folder."""
project = get_project(project_id)
if not project:
return jsonify({'error': 'Project not found'}), 404
folder = (request.json or {}).get('folder', '')
project['folder'] = folder
save_project(project_id, project)
return jsonify({'status': 'moved', 'folder': folder})
# ── Editing platform (NLE) selection ───────────────────────────────
@app.route('/api/projects/<project_id>/editing_platform', methods=['PATCH'])
def update_editing_platform(project_id):
"""Set the project's editing platform and remember the choice as the new global default."""
project = get_project(project_id)
if not project:
return jsonify({'error': 'Project not found'}), 404
data = request.json or {}
platform = data.get('platform')
if platform not in PLATFORMS:
return jsonify({'error': f'Invalid platform: {platform!r}'}), 400
project['editing_platform'] = platform
save_project(project_id, project)
prefs.set_default_platform(platform)
return jsonify({
'status': 'updated',
'editing_platform': platform,
'default_platform': prefs.get_default_platform(),
})
@app.route('/api/preferences/default_platform', methods=['GET'])
def get_default_platform_pref():
return jsonify({'platform': prefs.get_default_platform()})
@app.route('/api/preferences/default_platform', methods=['PATCH'])
def set_default_platform_pref():
data = request.json or {}
platform = data.get('platform')
if platform not in PLATFORMS:
return jsonify({'error': f'Invalid platform: {platform!r}'}), 400
prefs.set_default_platform(platform)
return jsonify({'platform': prefs.get_default_platform()})
@app.route('/api/ai-model/status', methods=['GET'])
def ai_model_status():
"""Return the current Gemma 4 variant plus per-variant speed/quality estimates.
When a ``?project_id=...`` is supplied, the ``estimated_casual`` on each
variant reflects the full analysis time for that project's transcript
(chunked per 15-minute slice × 2 AI calls per chunk). Without a project
context the estimate falls back to a single representative call, with the
casual phrase ending in "per call" rather than "for this project" so the
user isn't misled.
"""
import model_config
hw = model_config.detect_hardware_tier()
current = model_config.get_gemma4_variant()
project_id = (request.args.get('project_id') or '').strip()
project_context = None
total_seconds = None
if project_id:
p = get_project(project_id)
if p and p.get('transcript'):
segments = p['transcript'].get('segments', [])
if segments:
total_seconds = segments[-1].get('end', 0)
project_context = {
'project_id': project_id,
'project_name': p.get('name', 'Project'),
'duration_seconds': total_seconds,
}
variants = model_config.get_variant_estimates(hw, total_seconds=total_seconds)
# Resolve which model Ollama will ACTUALLY use on the next chat call.
# When the selected variant isn't downloaded, _get_ollama_model silently
# falls back to whatever IS downloaded — the UI uses this to warn the
# user that "Use this" didn't actually change anything.
try:
from ai_analysis import get_effective_ollama_model
effective_model, selected_variant, fallback_used = get_effective_ollama_model()
except Exception as e:
print(f"[ai-model/status] effective-model probe failed: {e}")
effective_model, selected_variant, fallback_used = (
current['variant'], current['variant'], False
)
return jsonify({
'hardware': {
'ram_gb': round(hw['ram_gb'], 1),
'arch': hw['arch'],
'arch_label': 'Apple Silicon' if hw['arch'].startswith('arm') else 'Intel',
'disk_gb': round(hw['disk_gb'], 1),
},
'current': {
'tier': current['tier'],
'variant': current['variant'],
'source': current['source'],
'reason': current.get('reason', ''),
},
'effective': {
'model': effective_model,
'selected_variant': selected_variant,
'fallback_used': fallback_used,
},
'variants': variants,
'project_context': project_context,
})
# ── BYO API key: error handler ──────────────────────────────────────
# Any AI feature endpoint that hits a missing-key, invalid-key, or
# rate-limit condition raises ``ProviderError`` from inside the provider
# layer. The errorhandler catches uncaught ones; routes with their own
# ``except Exception`` blocks should call ``_provider_error_response``
# from a more specific ``except ProviderError`` first.
def _provider_error_response(e):
"""Standardized JSON 400 for any ``ProviderError``.
Includes ``settings_url`` so the frontend can render a clickable link
(or button) that opens /settings — the user can fix the key without
leaving the AI feature they were using.
"""
return jsonify({
'error': str(e),
'code': getattr(e, 'code', '') or 'provider_error',
'settings_url': '/settings',
}), 400
@app.errorhandler(Exception)
def _handle_provider_error(e):
# Defense-in-depth: if anything in the ProviderError branch ever raises
# (e.g. jsonify fails on something exotic), re-raise the ORIGINAL
# exception so Flask logs the real cause. Otherwise the secondary error
# masks the root cause in server.log — exactly the bug from issue #25.
if isinstance(e, ProviderError):
try:
return _provider_error_response(e)
except Exception:
pass
raise e
# ── BYO API key: provider settings ──────────────────────────────────
# All AI calls route through ``ai_providers.get_active_provider()`` which
# reads ``provider_config.json`` from $DOZA_DATA_DIR. These three routes
# let the user select Local / Anthropic / OpenAI, paste an API key, and
# verify it before relying on it for analysis or chat.
@app.route('/settings/provider', methods=['GET'])
def get_provider_settings():
"""Return the current provider config with API keys masked for display."""
from ai_providers import load_provider_config, masked_config, has_api_key
cfg = load_provider_config()
out = masked_config(cfg)
# Source of truth is the Keychain (or the JSON fallback when Keychain is
# unavailable) — both are wrapped by has_api_key. The cfg dict's api_key
# field is hydrated the same way, so this is belt-and-braces, but it
# keeps the API contract explicit at the route boundary.
out['has_anthropic_key'] = has_api_key('anthropic')
out['has_openai_key'] = has_api_key('openai')
return jsonify(out)
@app.route('/settings/provider', methods=['POST'])
def save_provider_settings():
"""Save provider selection and/or API keys.
Body fields are all optional; whichever ones are present get updated.
An empty string clears that key. Returns the updated masked config.
"""
from ai_providers import load_provider_config, save_provider_config, masked_config
body = request.json or {}
cfg = load_provider_config()
active = body.get('active_provider')
if active in ('ollama', 'anthropic', 'openai'):
cfg['active_provider'] = active
# ``api_key`` is provider-scoped via the body's ``provider`` field, OR
# the saved active provider if the caller omits it. This keeps the
# frontend simple — it just sends {provider, api_key} when the user
# pastes a key into one of the provider panels.
target = body.get('provider') or cfg.get('active_provider')
if 'api_key' in body and target in ('anthropic', 'openai'):
cfg.setdefault(target, {})['api_key'] = (body.get('api_key') or '').strip()
if 'base_url' in body:
cfg.setdefault('ollama', {})['base_url'] = body['base_url'] or 'http://localhost:11434'
try:
save_provider_config(cfg)
except Exception as e:
return jsonify({'error': f'Save failed: {e}'}), 500
return jsonify(masked_config(cfg))
@app.route('/settings/provider/test', methods=['POST'])
def test_provider_connection():
"""Test a provider with the supplied (or saved) credentials.
Body: ``{"provider": "anthropic"|"openai"|"ollama", "api_key": "..."}``.
If ``api_key`` is omitted, falls back to the saved key. Sends a tiny
prompt and reports back ``{"success": bool, "error"|"response": "..."}``.
"""
from ai_providers import get_provider, load_provider_config
body = request.json or {}
name = (body.get('provider') or '').strip().lower()
if name not in ('ollama', 'anthropic', 'openai'):
return jsonify({'success': False, 'error': f'Unknown provider: {name!r}'}), 400
api_key = body.get('api_key') or ''
if name in ('anthropic', 'openai') and not api_key:
# Fall back to saved key.
cfg = load_provider_config()
api_key = (cfg.get(name) or {}).get('api_key') or ''
if name in ('anthropic', 'openai') and not api_key:
return jsonify({'success': False, 'error': 'No API key provided'}), 400
try:
if name == 'ollama':
provider = get_provider('ollama', model_resolver=_get_active_ollama_model)
else:
provider = get_provider(name, api_key=api_key)
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
try:
result = provider.test_connection()
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
return jsonify(result)
def _get_active_ollama_model():
"""Resolve the currently selected Ollama model tag.
Wrapped in app.py (rather than imported at module scope) so the
provider package stays decoupled from the OSS model_config helpers.
"""
from ai_analysis import _get_ollama_model
return _get_ollama_model()
@app.route('/api/ai-model', methods=['PATCH'])
def set_ai_model():
"""Switch the active Gemma 4 variant. Persists to model_config.json.
Body: ``{"tier": "small" | "medium" | "large" | "xlarge"}``.
"""
import model_config
data = request.json or {}
tier = data.get('tier', '').strip().lower()
try:
info = model_config.set_variant_manually(tier)
except ValueError as e:
return jsonify({'error': str(e)}), 400
# Evict any other models from VRAM. Ollama's default keep_alive=30m
# keeps the previous variant resident, so on lower-RAM Macs you end
# up with two Gemma weights in unified memory at once → Metal
# compaction stalls.
new_variant = info['variant']
try:
import requests as _req
ps = _req.get('http://127.0.0.1:11434/api/ps', timeout=2).json()
for m in ps.get('models', []):
name = m.get('name')
if name and name != new_variant:
_req.post(
'http://127.0.0.1:11434/api/generate',
json={'model': name, 'keep_alive': 0, 'prompt': ''},
timeout=2,
)
except Exception as e:
print(f"[ai-model] eviction failed: {e}")
return jsonify({
'tier': info['tier'],
'variant': info['variant'],
'description': info['description'],
'source': info['source'],
})
@app.route('/api/ai-model/pull', methods=['POST'])
def pull_ai_model():
"""Stream Ollama's download progress for a Gemma variant as NDJSON.
Body: ``{"tier": "small" | "medium" | "large" | "xlarge"}``.
Each line is a JSON object matching Ollama's ``/api/pull`` event schema,
roughly:
- ``{"status": "pulling manifest"}``
- ``{"status": "downloading", "digest": "...", "total": N, "completed": M}``
- ``{"status": "success"}``
- ``{"status": "error", "message": "..."}`` (our synthetic terminus on failure)
The frontend consumes these to render a progress bar in the AI Model
settings modal and refresh the "downloaded" badges when the pull ends.
"""
import model_config
import requests as _requests
data = request.json or {}
tier = data.get('tier', '').strip().lower()
if tier not in model_config.VALID_TIERS:
return jsonify({'error': f'invalid tier {tier!r}'}), 400
variant, _size, _desc = model_config.GEMMA4_VARIANTS[tier]
def _err_event(message: str) -> bytes:
return (json.dumps({'status': 'error', 'message': message}) + '\n').encode('utf-8')
def generate():
try:
upstream = _requests.post(
'http://localhost:11434/api/pull',
json={'name': variant, 'stream': True},
stream=True,
timeout=None,
)
if upstream.status_code != 200:
yield _err_event(f'Ollama pull failed with HTTP {upstream.status_code}')
return
# iter_lines(decode_unicode=True) only actually decodes when the
# upstream response exposes an encoding. Ollama's /api/pull
# doesn't, so we stay in bytes-land end-to-end — mixing str and
# bytes chunks in a Flask streaming response crashes with
# "can't concat str to bytes".
for line in upstream.iter_lines():
if line:
yield line + b'\n'
except _requests.exceptions.ConnectionError:
yield _err_event('Could not reach Ollama at localhost:11434. Is the Ollama app running?')
except Exception as e:
yield _err_event(str(e))
from flask import Response
return Response(generate(), mimetype='application/x-ndjson')
def create_project_from_path(
source_path,
project_name=None,
client_name='',
interviewer_name='Interviewer',
subject_name='Subject',
num_speakers=2,
language='en',
project_id=None,
):
"""Create a new project from a file already on disk. Returns project_id.
The source file is NOT copied or moved — meta.json points at it in
place. Both the path-based ``/create`` route and CLI / scripted
callers (e.g. batch importers) use this directly. The byte-stream
``/upload`` route saves the uploaded file into the project dir
first, then calls this with ``project_id`` set so the same id is
reused for the dir + meta (rather than generating a new one and
leaving the saved bytes orphaned).
Validation raises ``ValueError`` on a missing file, a non-file path,
or an unsupported extension. FCPXML inputs are auto-ingested via the
same ``_ingest_fcpxml`` path the routes use. Failure during ingest
cleans up the half-created project directory before re-raising so a
bad input never leaves a dangling empty project on disk.
Args:
source_path: absolute path to a media file or .fcpxml(d) on disk.
project_name: display name. Defaults to the filename stem with
underscores/hyphens turned into spaces.
client_name, interviewer_name, subject_name, num_speakers,
language: optional metadata fields persisted on meta.json.
project_id: if provided, use this id instead of generating one.
Lets ``/upload`` create the project dir and save bytes into it
before the meta is written.
"""
source_path = os.path.expanduser(source_path)
is_fcpxml = _is_fcpxml_input(source_path)
if not is_fcpxml and not os.path.isfile(source_path):
raise ValueError(f'Path is not a file: {source_path}')
if not is_fcpxml and not allowed_file(source_path):
ext = source_path.rsplit('.', 1)[-1].lower() if '.' in source_path else 'unknown'
raise ValueError(f'Unsupported file type: .{ext}')
if project_id is None:
project_id = str(uuid.uuid4())[:8]
project_dir = os.path.join(app.config['PROJECTS_DIR'], project_id)
os.makedirs(project_dir, exist_ok=True)
fcpxml_meta = None
if is_fcpxml:
try:
ingest = _ingest_fcpxml(source_path, project_dir)
except ValueError:
shutil.rmtree(project_dir, ignore_errors=True)
raise
audio_path = ingest['audio_path']
fcpxml_meta = ingest['fcpxml_source']
if not project_name:
project_name = fcpxml_meta.get('project_name') or Path(source_path).stem
media_source_path = audio_path
else:
if not project_name:
project_name = Path(source_path).stem.replace('_', ' ').replace('-', ' ')
media_source_path = source_path
file_size = os.path.getsize(media_source_path)
meta = {
'id': project_id,
'name': project_name,
'client_name': client_name,
'interviewer_name': interviewer_name or 'Interviewer',
'subject_name': subject_name or 'Subject',
'num_speakers': num_speakers,
'language': language or 'en',
'filename': os.path.basename(media_source_path),
'source_path': media_source_path,
'filepath': media_source_path,
'file_size': file_size,
'file_size_formatted': format_file_size(file_size),
'created_at': datetime.now().isoformat(),
'status': 'uploaded',
'transcript': None,
'analysis': None,
'client_selects': [],
'social_clips': [],
'editing_platform': prefs.get_default_platform(),
}
if fcpxml_meta is not None:
meta['fcpxml_source'] = fcpxml_meta
save_project(project_id, meta)
return project_id
@app.route('/create', methods=['POST'])
def create_project():
"""Create a new project from a local file path."""
data = request.json or {}
source_path = data.get('source_path', '').strip()
if not source_path:
return jsonify({'error': 'No file path provided'}), 400
# Expand user home directory before existence check so ~/foo works.
expanded = os.path.expanduser(source_path)
if not os.path.exists(expanded):
return jsonify({'error': f'File not found: {expanded}'}), 400
try:
project_id = create_project_from_path(
expanded,
project_name=data.get('project_name', '').strip() or None,
client_name=data.get('client_name', '').strip(),
interviewer_name=data.get('interviewer_name', 'Interviewer').strip(),
subject_name=data.get('subject_name', 'Subject').strip(),
num_speakers=int(data.get('num_speakers', 2)),
language=data.get('language', 'en').strip(),
)
except ValueError as e:
return jsonify({'error': str(e)}), 400
return jsonify({'project_id': project_id, 'status': 'created'})
@app.route('/upload', methods=['POST'])
def upload():
"""Handle small file upload via drag-and-drop (under 500MB)."""
if 'file' not in request.files:
return jsonify({'error': 'No file provided'}), 400
file = request.files['file']
if file.filename == '' or not allowed_file(file.filename):
return jsonify({'error': 'Invalid file type'}), 400
project_name = request.form.get('project_name', '').strip()
client_name = request.form.get('client_name', '').strip()
interviewer_name = request.form.get('interviewer_name', 'Interviewer').strip()
subject_name = request.form.get('subject_name', 'Subject').strip()
language = request.form.get('language', 'en').strip()
if not project_name:
project_name = file.filename.rsplit('.', 1)[0]
# Generate the project id and dir up front so we have somewhere to
# land the uploaded bytes. We then hand the saved path to
# create_project_from_path with the same project_id, so the meta file
# ends up in the same dir as the file (rather than the function
# generating a fresh id and orphaning what we just saved).
project_id = str(uuid.uuid4())[:8]
project_dir = os.path.join(app.config['PROJECTS_DIR'], project_id)
os.makedirs(project_dir, exist_ok=True)
filename = secure_filename(file.filename)
filepath = os.path.join(project_dir, filename)
file.save(filepath)
try:
create_project_from_path(
filepath,
project_name=project_name,
client_name=client_name,
interviewer_name=interviewer_name,
subject_name=subject_name,
language=language,
project_id=project_id,
)
except ValueError as e:
# File was already saved into project_dir; clean up so a bad
# upload doesn't leave an orphan dir behind.
shutil.rmtree(project_dir, ignore_errors=True)
return jsonify({'error': str(e)}), 400
return jsonify({'project_id': project_id, 'status': 'uploaded'})
@app.route('/find-file', methods=['POST'])
def find_file():
"""Find a file's full path by name and size (used when drag-and-dropping)."""
data = request.json or {}
filename = data.get('filename', '').strip()
file_size = data.get('size', 0)
if not filename:
return jsonify({'error': 'No filename provided'}), 400
home = str(Path.home())
search_roots = ['/Volumes']
for d in ['Desktop', 'Documents', 'Movies', 'Downloads', 'Music']:
p = os.path.join(home, d)
if os.path.exists(p):
search_roots.append(p)
matches = []
seen = set()
# FCP package bundles (e.g. .fcpxmld) are directories on disk, but the
# browser drag-drop reports them as a single "file" with size 0. Match
# on dirnames and skip size-checking when the target is a bundle.
is_bundle = filename.lower().endswith(('.fcpxmld', '.fcpbundle'))
for root_dir in search_roots:
try:
for dirpath, dirnames, filenames in os.walk(root_dir, followlinks=True):
# Match bundle before we prune — a bundle is a dir that happens
# to match the target name.
if is_bundle and filename in dirnames:
target_path = os.path.join(dirpath, filename)
real_path = os.path.realpath(target_path)
if real_path not in seen:
seen.add(real_path)
matches.append({
'path': target_path,
'size': 0,
'size_formatted': 'bundle',
})
# Prune: skip hidden/system dirs, and don't descend into any
# package bundle (otherwise we'd walk every .fcpxmld's internals).
dirnames[:] = [
d for d in dirnames
if not d.startswith('.')
and d not in ('node_modules', '__pycache__', '.Trash')
and not d.lower().endswith(('.fcpxmld', '.fcpbundle'))
]
if filename in filenames:
full_path = os.path.join(dirpath, filename)
real_path = os.path.realpath(full_path)
if real_path in seen:
continue
seen.add(real_path)
try:
stat = os.stat(full_path)
# Match by size if provided (within 1% tolerance for filesystem differences)
if file_size > 0:
size_diff = abs(stat.st_size - file_size)
tolerance = max(file_size * 0.01, 4096)
if size_diff <= tolerance:
matches.append({
'path': full_path,
'size': stat.st_size,
'size_formatted': format_file_size(stat.st_size),
})
else:
matches.append({
'path': full_path,
'size': stat.st_size,
'size_formatted': format_file_size(stat.st_size),