-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.py
More file actions
2123 lines (1714 loc) · 73.7 KB
/
main.py
File metadata and controls
2123 lines (1714 loc) · 73.7 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 os
import pickle
import queue
import re
import threading
import time
import gc
from contextlib import contextmanager
import pytesseract
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from PyPDF2 import PdfReader
from pdf2image import convert_from_path
from docx import Document
import requests
import logging
import yaml
import json
import shutil
import ffmpeg
import whisperx
DOCUMENT_EXTENSIONS = (".pdf", ".docx", ".txt")
AUDIO_EXTENSIONS = (
".mp3",
".wav",
".m4a",
".aac",
".flac",
".ogg",
".opus",
".wma",
".aiff",
".aif",
".mpga",
".mp2",
".m4b",
".mka",
".amr",
".ac3",
)
VIDEO_EXTENSIONS = (".mp4", ".avi", ".mov", ".mkv", ".webm", ".m4v")
SUPPORTED_EXTENSIONS = DOCUMENT_EXTENSIONS + AUDIO_EXTENSIONS + VIDEO_EXTENSIONS
TEMP_FILE_SUFFIXES = (".part", ".tmp", ".crdownload")
APP_ROOT = "/app"
DEFAULT_INCOMING_PATH = f"{APP_ROOT}/incoming"
DEFAULT_VAULT_PATH = f"{APP_ROOT}/vault"
DEFAULT_CONFIG_DIR = f"{APP_ROOT}/config"
DEFAULT_CONFIG_DEFAULTS_DIR = f"{APP_ROOT}/config-defaults"
DEFAULT_CONFIG_PATH = f"{DEFAULT_CONFIG_DIR}/config.yml"
DEFAULT_CONFIG_FALLBACK_PATH = f"{DEFAULT_CONFIG_DEFAULTS_DIR}/config.yml"
LEGACY_CONFIG_PATH = f"{APP_ROOT}/config.yml"
DEFAULT_SUMMARY_PROMPT_NAME = "summarize-notes.md"
DEFAULT_SUMMARY_PROMPT_PATH = f"{DEFAULT_CONFIG_DIR}/{DEFAULT_SUMMARY_PROMPT_NAME}"
DEFAULT_SUMMARY_PROMPT_FALLBACK_PATH = f"{DEFAULT_CONFIG_DEFAULTS_DIR}/{DEFAULT_SUMMARY_PROMPT_NAME}"
DEFAULT_TRANSCRIPT_FORMAT_PROMPT_NAME = "format-transcript.md"
DEFAULT_TRANSCRIPT_FORMAT_PROMPT_PATH = f"{DEFAULT_CONFIG_DIR}/{DEFAULT_TRANSCRIPT_FORMAT_PROMPT_NAME}"
DEFAULT_OBSIDIAN_EXTRACT_PROMPT_NAME = "obsidian-extract.md"
DEFAULT_OBSIDIAN_EXTRACT_PROMPT_PATH = f"{DEFAULT_CONFIG_DIR}/{DEFAULT_OBSIDIAN_EXTRACT_PROMPT_NAME}"
DEFAULT_OBSIDIAN_EXTRACT_PROMPT_FALLBACK_PATH = f"{DEFAULT_CONFIG_DEFAULTS_DIR}/{DEFAULT_OBSIDIAN_EXTRACT_PROMPT_NAME}"
DEFAULT_OBSIDIAN_TEMPLATE_NAME = "obsidian-template.md"
DEFAULT_OBSIDIAN_TEMPLATE_PATH = f"{DEFAULT_CONFIG_DIR}/{DEFAULT_OBSIDIAN_TEMPLATE_NAME}"
DEFAULT_LLM_TIMEOUT_SECONDS = 120
DEFAULT_CHUNK_MAX_INPUT_CHARS = 24000
DEFAULT_CHUNK_TARGET_CHARS = 16000
DEFAULT_CHUNK_OVERLAP_CHARS = 400
DEFAULT_INCOMING_RESCAN_INTERVAL_SECONDS = 5
DEFAULT_GPU_WHISPER_BATCH_SIZE = 16
DEFAULT_CPU_WHISPER_BATCH_SIZE = 4
DEFAULT_GPU_MIN_BATCH_SIZE = 1
DEFAULT_GPU_OOM_FALLBACK = "cpu"
TORCH_LOAD_PATCH_LOCK = threading.Lock()
DEFAULT_TRANSCRIPT_FORMAT_PROMPT = """Rewrite the following raw transcript as clean, readable Markdown.
## Goals
- Preserve the speaker meaning and factual content.
- Fix obvious transcription punctuation and paragraph breaks.
- Group the transcript into readable paragraphs.
- Keep names, technical terms, and numbers intact when possible.
## Output Instructions
- Output only the formatted transcript in Markdown.
- Start with a single `# Transcript` heading.
- Do not summarize or omit content.
- Do not add commentary, warnings, or analysis.
- Do not invent speaker names.
"""
DEFAULT_OBSIDIAN_TEMPLATE = """{{frontmatter}}
# {{title}}
## Audio
![[{{audio_filename}}]]
## Files
- Transcript: [[{{transcript_filename}}]]
{{summary_file_line}}
## Linked Entities
{{entity_links_section}}
## Summary
{{summary_content}}
## Context
{{context_section}}
## Main Ideas
{{main_ideas_section}}
## Decisions
{{decisions_section}}
## Action Items
{{action_items_section}}
## Challenges and Risks
{{challenges_and_risks_section}}
## Next Steps
{{next_steps_section}}
## Transcript
{{transcript_body}}
"""
DEFAULT_OBSIDIAN_EXTRACT_PROMPT = """Extract structured Obsidian note data from the following transcript or summary.
Return JSON only. Do not return Markdown. Do not wrap the JSON in code fences.
Schema:
{
"context": "string or null",
"main_ideas": ["string"],
"decisions": ["string"],
"action_items": ["string"],
"recommendations": ["string"],
"insights": ["string"],
"challenges_and_risks": ["string"],
"next_steps": ["string"],
"inferred_people": ["string"],
"inferred_projects": ["string"],
"inferred_topics": ["string"],
"inferred_context": "string or null",
"inferred_meeting_type": "string or null"
}
Rules:
- Use only information supported by the input.
- Never invent names, roles, deadlines, projects, or actions.
- `inferred_*` fields may contain careful interpretation, but only when strongly supported.
- Keep list items short and atomic.
- Use empty arrays when nothing is present.
- Use null for unknown single-value fields.
"""
# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Load config
def load_config(config_path=None):
if not config_path:
config_path = (
os.environ.get("ECHONOTES_CONFIG_PATH")
or first_existing_path(DEFAULT_CONFIG_PATH, DEFAULT_CONFIG_FALLBACK_PATH, LEGACY_CONFIG_PATH)
or DEFAULT_CONFIG_PATH
)
try:
with open(config_path, 'r') as f:
return yaml.safe_load(f)
except FileNotFoundError:
logging.error(f"Configuration file not found at {config_path}. Please ensure the file exists.")
raise
except yaml.YAMLError as e:
logging.error(f"Error reading configuration file {config_path}: {e}")
raise
def get_worker_count(config):
configured_count = config.get("worker_count")
if configured_count:
return max(1, int(configured_count))
try:
import torch
if torch.cuda.is_available():
return 1
except Exception:
pass
return max(1, min(4, os.cpu_count() or 1))
def get_default_whisper_model():
try:
import torch
if torch.cuda.is_available():
return "small"
except Exception:
pass
return "base"
def get_llm_settings(config):
llm_settings = config.get("llm")
if isinstance(llm_settings, dict):
return llm_settings
if config.get("api_url") or config.get("model"):
return {
"provider": "legacy_generate",
"api_url": config.get("api_url"),
"api_key": config.get("bearer_token"),
"model": config.get("model"),
}
return {}
def get_chunking_settings(config):
chunking = config.get("chunking", {})
return {
"enabled": chunking.get("enabled", True),
"max_input_chars": int(chunking.get("max_input_chars", DEFAULT_CHUNK_MAX_INPUT_CHARS)),
"target_chunk_chars": int(chunking.get("target_chunk_chars", DEFAULT_CHUNK_TARGET_CHARS)),
"overlap_chars": int(chunking.get("overlap_chars", DEFAULT_CHUNK_OVERLAP_CHARS)),
}
def get_diarization_settings(config):
return {
"enabled": bool(config.get("diarization_enabled", True)),
"hf_token": (config.get("diarization_hf_token") or "").strip(),
"model_name": (config.get("diarization_model_name") or "").strip() or None,
"num_speakers": config.get("diarization_num_speakers"),
"min_speakers": config.get("diarization_min_speakers"),
"max_speakers": config.get("diarization_max_speakers"),
}
def get_transcription_runtime_settings(config):
configured_batch_size = config.get("whisper_batch_size")
configured_min_batch_size = config.get("whisper_min_batch_size")
gpu_oom_fallback = (config.get("gpu_oom_fallback") or DEFAULT_GPU_OOM_FALLBACK).strip().lower()
batch_size = int(configured_batch_size) if configured_batch_size not in (None, "") else None
min_batch_size = (
int(configured_min_batch_size)
if configured_min_batch_size not in (None, "")
else DEFAULT_GPU_MIN_BATCH_SIZE
)
return {
"batch_size": batch_size,
"min_batch_size": max(1, min_batch_size),
"gpu_oom_fallback": gpu_oom_fallback if gpu_oom_fallback in ("cpu", "fail") else DEFAULT_GPU_OOM_FALLBACK,
}
def get_file_extension(file_path):
return os.path.splitext(file_path)[1].lower()
def is_audio_file(file_path):
return get_file_extension(file_path) in AUDIO_EXTENSIONS
def is_video_file(file_path):
return get_file_extension(file_path) in VIDEO_EXTENSIONS
def is_supported_file(file_path):
return get_file_extension(file_path) in SUPPORTED_EXTENSIONS
def join_text_content(content):
if isinstance(content, str):
return content
if isinstance(content, list):
text_parts = []
for item in content:
if isinstance(item, str):
text_parts.append(item)
elif isinstance(item, dict):
if isinstance(item.get("text"), str):
text_parts.append(item["text"])
elif isinstance(item.get("content"), str):
text_parts.append(item["content"])
return "".join(text_parts)
return ""
class BaseLLMClient:
def __init__(self, settings):
self.settings = settings
self.provider = settings.get("provider")
self.model = settings.get("model")
self.timeout_seconds = self._parse_timeout_seconds(settings.get("timeout_seconds", DEFAULT_LLM_TIMEOUT_SECONDS))
self.temperature = settings.get("temperature")
self.max_tokens = settings.get("max_tokens")
def generate(self, prompt):
raise NotImplementedError
@staticmethod
def _parse_timeout_seconds(timeout_value):
if timeout_value is None:
return None
if isinstance(timeout_value, str):
normalized = timeout_value.strip().lower()
if normalized in ("", "none", "null", "false", "off"):
return None
timeout_value = normalized
timeout_seconds = float(timeout_value)
if timeout_seconds <= 0:
return None
return timeout_seconds
def _post_json(self, url, headers, payload):
response = requests.post(url, json=payload, headers=headers, timeout=self.timeout_seconds)
response.raise_for_status()
return response.json()
class RecoverableProcessingError(RuntimeError):
pass
class LegacyGenerateClient(BaseLLMClient):
def generate(self, prompt):
headers = {"Content-Type": "application/json"}
api_key = self.settings.get("api_key")
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
payload = {
"model": self.model,
"prompt": prompt,
"stream": False,
}
response = self._post_json(self.settings["api_url"], headers, payload)
return response.get("response", "")
class OllamaClient(BaseLLMClient):
def generate(self, prompt):
base_url = self.settings.get("base_url", "http://localhost:11434/api").rstrip("/")
headers = {"Content-Type": "application/json"}
api_key = self.settings.get("api_key")
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
payload = {
"model": self.model,
"prompt": prompt,
"stream": False,
}
response = self._post_json(f"{base_url}/generate", headers, payload)
return response.get("response", "")
class OpenAICompatibleClient(BaseLLMClient):
def __init__(self, settings, base_url, path, extra_headers=None):
super().__init__(settings)
self.base_url = base_url.rstrip("/")
self.path = path
self.extra_headers = extra_headers or {}
def generate(self, prompt):
headers = {
"Content-Type": "application/json",
**self.extra_headers,
}
api_key = self.settings.get("api_key")
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
payload = {
"model": self.model,
"messages": [{"role": "user", "content": prompt}],
"stream": False,
}
if self.temperature is not None:
payload["temperature"] = self.temperature
if self.max_tokens is not None:
payload["max_tokens"] = self.max_tokens
response = self._post_json(f"{self.base_url}{self.path}", headers, payload)
message = response.get("choices", [{}])[0].get("message", {})
return join_text_content(message.get("content", ""))
class AnthropicClient(BaseLLMClient):
def generate(self, prompt):
base_url = self.settings.get("base_url", "https://api.anthropic.com").rstrip("/")
headers = {
"Content-Type": "application/json",
"x-api-key": self.settings.get("api_key", ""),
"anthropic-version": self.settings.get("anthropic_version", "2023-06-01"),
}
payload = {
"model": self.model,
"messages": [{"role": "user", "content": prompt}],
"max_tokens": int(self.max_tokens or 2048),
}
if self.temperature is not None:
payload["temperature"] = self.temperature
response = self._post_json(f"{base_url}/v1/messages", headers, payload)
return join_text_content(response.get("content", []))
def build_llm_client(config):
settings = get_llm_settings(config)
provider = (settings.get("provider") or "").strip().lower()
if not provider:
logging.info("No LLM provider configured; LLM-based formatting and summarization will be skipped.")
return None
if not settings.get("model") and provider != "legacy_generate":
raise ValueError(f"LLM provider '{provider}' requires a model to be configured")
if provider == "legacy_generate":
if not settings.get("api_url"):
raise ValueError("legacy_generate provider requires api_url")
return LegacyGenerateClient(settings)
if provider == "ollama":
return OllamaClient(settings)
if provider == "openai":
base_url = settings.get("base_url", "https://api.openai.com/v1")
return OpenAICompatibleClient(settings, base_url, "/chat/completions")
if provider == "openrouter":
base_url = settings.get("base_url", "https://openrouter.ai/api/v1")
extra_headers = {}
if settings.get("site_url"):
extra_headers["HTTP-Referer"] = settings["site_url"]
if settings.get("site_name"):
extra_headers["X-Title"] = settings["site_name"]
return OpenAICompatibleClient(settings, base_url, "/chat/completions", extra_headers)
if provider == "openwebui":
base_url = settings.get("base_url", "http://localhost:3000/api")
return OpenAICompatibleClient(settings, base_url, "/chat/completions")
if provider in ("claude", "anthropic"):
return AnthropicClient(settings)
raise ValueError(f"Unsupported LLM provider: {provider}")
def load_prompt(prompt_path, default_content):
if prompt_path and os.path.exists(prompt_path):
with open(prompt_path, 'r') as prompt_file:
return prompt_file.read()
return default_content
def first_existing_path(*paths):
for path in paths:
if path and os.path.exists(path):
return path
return None
def resolve_config_asset_path(configured_path, default_path, fallback_path=None):
if configured_path and os.path.exists(configured_path):
return configured_path
if configured_path:
logging.warning(f"Configured path does not exist, falling back to defaults: {configured_path}")
return first_existing_path(default_path, fallback_path) or configured_path or default_path or fallback_path
def path_has_hidden_component(path, root_path=None):
if not path:
return False
normalized_path = os.path.normpath(path)
if root_path:
normalized_root = os.path.normpath(root_path)
try:
normalized_path = os.path.relpath(normalized_path, normalized_root)
except ValueError:
pass
parts = [part for part in normalized_path.split(os.sep) if part not in ("", ".", "..")]
return any(part.startswith(".") for part in parts)
def strip_outer_fenced_block(text):
if not isinstance(text, str):
return ""
stripped = text.strip()
if not stripped:
return ""
for fence in ("```", "~~~"):
if not stripped.startswith(fence):
continue
lines = stripped.splitlines()
if len(lines) < 2:
return stripped
if lines[0].strip().startswith(fence) and lines[-1].strip() == fence:
return "\n".join(lines[1:-1]).strip()
return stripped
def sanitize_markdown_output(text):
return strip_outer_fenced_block((text or "").replace("\r\n", "\n")).strip()
@contextmanager
def whisperx_torch_load_compat():
try:
import torch
from omegaconf import DictConfig, ListConfig
from omegaconf.base import ContainerMetadata
except Exception:
yield
return
serialization = getattr(torch, "serialization", None)
if serialization and hasattr(serialization, "add_safe_globals"):
try:
serialization.add_safe_globals([ListConfig, DictConfig, ContainerMetadata])
except Exception as safe_globals_error:
logging.debug(f"Unable to register torch safe globals for WhisperX: {safe_globals_error}")
original_torch_load = torch.load
def compat_torch_load(*args, **kwargs):
try:
return original_torch_load(*args, **kwargs)
except pickle.UnpicklingError as exc:
if kwargs.get("weights_only", True) is False:
raise
if "Weights only load failed" not in str(exc):
raise
retry_kwargs = dict(kwargs)
retry_kwargs["weights_only"] = False
if args and hasattr(args[0], "seek"):
try:
args[0].seek(0)
except Exception as seek_error:
logging.debug(f"Unable to rewind checkpoint stream before torch.load retry: {seek_error}")
logging.warning(
"Retrying torch.load with weights_only=False for WhisperX/pyannote checkpoint compatibility"
)
return original_torch_load(*args, **retry_kwargs)
with TORCH_LOAD_PATCH_LOCK:
torch.load = compat_torch_load
try:
yield
finally:
torch.load = original_torch_load
def get_summary_prompt_path(config):
return resolve_config_asset_path(
config.get("summary_prompt_path"),
DEFAULT_SUMMARY_PROMPT_PATH,
DEFAULT_SUMMARY_PROMPT_FALLBACK_PATH,
)
def get_transcript_format_prompt_path(config):
return resolve_config_asset_path(
config.get("transcript_format_prompt_path"),
DEFAULT_TRANSCRIPT_FORMAT_PROMPT_PATH,
)
def get_obsidian_extract_prompt_path(config):
return resolve_config_asset_path(
config.get("obsidian_extract_prompt_path"),
DEFAULT_OBSIDIAN_EXTRACT_PROMPT_PATH,
DEFAULT_OBSIDIAN_EXTRACT_PROMPT_FALLBACK_PATH,
)
def get_obsidian_template_path(config):
return resolve_config_asset_path(
config.get("obsidian_template_path"),
DEFAULT_OBSIDIAN_TEMPLATE_PATH,
os.path.join(os.path.dirname(get_summary_prompt_path(config)), DEFAULT_OBSIDIAN_TEMPLATE_NAME),
)
def get_vault_path(config):
return config.get("vault_path", DEFAULT_VAULT_PATH)
def get_watch_path(config):
return config.get("path_to_watch", DEFAULT_INCOMING_PATH)
def get_incoming_rescan_interval_seconds(config):
configured_interval = config.get("incoming_rescan_interval_seconds")
if configured_interval in (None, ""):
return DEFAULT_INCOMING_RESCAN_INTERVAL_SECONDS
return max(0, int(configured_interval))
def render_template(template, context):
rendered = template
for key, value in context.items():
rendered = rendered.replace(f"{{{{{key}}}}}", value)
return rendered
def sanitize_json_output(text):
sanitized = strip_outer_fenced_block((text or "").replace("\r\n", "\n")).strip()
if not sanitized:
raise ValueError("Structured JSON output is empty")
try:
return json.loads(sanitized)
except json.JSONDecodeError:
start = sanitized.find("{")
end = sanitized.rfind("}")
if start == -1 or end == -1 or end <= start:
raise
return json.loads(sanitized[start : end + 1])
def normalize_optional_string(value):
if value is None:
return None
text = str(value).strip()
return text or None
def normalize_string_list(values):
if not isinstance(values, list):
return []
normalized = []
seen = set()
for value in values:
text = normalize_optional_string(value)
if not text:
continue
key = text.casefold()
if key in seen:
continue
seen.add(key)
normalized.append(text)
return normalized
def normalize_obsidian_structured_data(data):
if not isinstance(data, dict):
data = {}
return {
"context": normalize_optional_string(data.get("context")),
"main_ideas": normalize_string_list(data.get("main_ideas")),
"decisions": normalize_string_list(data.get("decisions")),
"action_items": normalize_string_list(data.get("action_items")),
"recommendations": normalize_string_list(data.get("recommendations")),
"insights": normalize_string_list(data.get("insights")),
"challenges_and_risks": normalize_string_list(data.get("challenges_and_risks")),
"next_steps": normalize_string_list(data.get("next_steps")),
"inferred_people": normalize_string_list(data.get("inferred_people")),
"inferred_projects": normalize_string_list(data.get("inferred_projects")),
"inferred_topics": normalize_string_list(data.get("inferred_topics")),
"inferred_context": normalize_optional_string(data.get("inferred_context")),
"inferred_meeting_type": normalize_optional_string(data.get("inferred_meeting_type")),
}
def render_markdown_bullets(items):
if not items:
return "None stated."
return "\n".join(f"- {item}" for item in items)
def strip_leading_markdown_heading(text):
if not text:
return ""
lines = text.splitlines()
if not lines:
return ""
if not lines[0].lstrip().startswith("#"):
return text
index = 1
while index < len(lines) and not lines[index].strip():
index += 1
return "\n".join(lines[index:]).strip()
def sanitize_obsidian_link_target(value):
if not value:
return None
return re.sub(r'[\[\]\|#^]', "", value).strip() or None
def render_entity_links_section(label, folder_name, items):
normalized_items = []
seen = set()
for item in items:
link_target = sanitize_obsidian_link_target(item)
if not link_target:
continue
key = link_target.casefold()
if key in seen:
continue
seen.add(key)
normalized_items.append(f"[[{folder_name}/{link_target}]]")
if not normalized_items:
return None
return f"- {label}: " + ", ".join(normalized_items)
def render_frontmatter(metadata):
return "---\n" + yaml.safe_dump(metadata, sort_keys=False, allow_unicode=False).strip() + "\n---"
def format_filesystem_timestamp(timestamp_value):
if timestamp_value is None:
return None
return time.strftime("%Y-%m-%dT%H:%M:%S%z", time.localtime(timestamp_value))
def get_source_file_metadata(source_path):
try:
stat = os.stat(source_path)
except OSError:
return {"source_created": None, "source_modified": None}
source_created = None
if hasattr(stat, "st_birthtime"):
source_created = format_filesystem_timestamp(stat.st_birthtime)
return {
"source_created": source_created,
"source_modified": format_filesystem_timestamp(stat.st_mtime),
}
def format_timestamp_link(seconds):
total_seconds = max(0, int(seconds))
hours, remainder = divmod(total_seconds, 3600)
minutes, secs = divmod(remainder, 60)
if hours:
display = f"{hours:02d}:{minutes:02d}:{secs:02d}"
else:
display = f"{minutes:02d}:{secs:02d}"
return total_seconds, display
def build_linked_transcript(audio_filename, segments):
lines = []
for segment in segments:
text = segment.get("text", "").strip()
if not text:
continue
start_seconds, display_time = format_timestamp_link(segment.get("start", 0))
speaker = segment.get("speaker")
speaker_prefix = f"{speaker}: " if speaker else ""
lines.append(
f"[[{audio_filename}#t={start_seconds}|{display_time}]] {speaker_prefix}{text}"
)
return "\n".join(lines).strip()
def normalize_speaker_name(raw_speaker, speaker_names):
if not raw_speaker:
return None
if raw_speaker not in speaker_names:
speaker_names[raw_speaker] = f"Speaker {len(speaker_names) + 1}"
return speaker_names[raw_speaker]
def normalize_diarization_turns(diarization_segments):
if diarization_segments is None:
return []
if hasattr(diarization_segments, "itertuples"):
turns = []
for row in diarization_segments.itertuples(index=False):
speaker = getattr(row, "speaker", None)
start = getattr(row, "start", None)
end = getattr(row, "end", None)
if speaker is None or start is None or end is None:
continue
turns.append(
{
"start": float(start),
"end": float(end),
"speaker": speaker,
}
)
return turns
turns = []
for segment in diarization_segments:
speaker = segment.get("speaker")
start = segment.get("start")
end = segment.get("end")
if speaker is None or start is None or end is None:
continue
turns.append(
{
"start": float(start),
"end": float(end),
"speaker": speaker,
}
)
return turns
def get_speaker_for_interval(start, end, diarization_turns):
if not diarization_turns:
return None
interval_start = float(start or 0)
interval_end = float(end if end is not None else interval_start)
if interval_end < interval_start:
interval_end = interval_start
best_speaker = None
best_overlap = 0.0
for turn in diarization_turns:
overlap = min(interval_end, turn["end"]) - max(interval_start, turn["start"])
if overlap > best_overlap:
best_overlap = overlap
best_speaker = turn["speaker"]
if best_speaker:
return best_speaker
midpoint = (interval_start + interval_end) / 2
nearest_turn = min(
diarization_turns,
key=lambda turn: min(abs(midpoint - turn["start"]), abs(midpoint - turn["end"])),
)
return nearest_turn["speaker"]
def combine_word_tokens(words):
tokens = [word.get("text", "").strip() for word in words if word.get("text", "").strip()]
return " ".join(tokens).strip()
def append_speakerized_segment(target, words, fallback_segment=None):
if not words:
return
text = combine_word_tokens(words)
if not text:
return
segment_start = words[0].get("start")
segment_end = words[-1].get("end")
if segment_start is None and fallback_segment:
segment_start = fallback_segment.get("start", 0)
if segment_end is None and fallback_segment:
segment_end = fallback_segment.get("end")
target.append(
{
"start": segment_start if segment_start is not None else 0,
"end": segment_end,
"text": text,
"speaker": words[0].get("speaker"),
}
)
def assign_diarization_to_transcript_segments(segments, diarization_segments):
diarization_turns = normalize_diarization_turns(diarization_segments)
if not diarization_turns:
return segments
speakerized_segments = []
for segment in segments:
words = segment.get("words") or []
aligned_words = []
for word in words:
text = (word.get("word") or "").strip()
if not text:
continue
word_start = word.get("start", segment.get("start", 0))
word_end = word.get("end")
if word_end is None:
word_end = word_start if word_start is not None else segment.get("end")
aligned_words.append(
{
"text": text,
"start": word_start,
"end": word_end,
"speaker": get_speaker_for_interval(word_start, word_end, diarization_turns),
}
)
if aligned_words:
current_words = []
current_speaker = None
for word in aligned_words:
word_speaker = word.get("speaker")
if current_words and word_speaker != current_speaker:
append_speakerized_segment(speakerized_segments, current_words, segment)
current_words = []
current_words.append(word)
current_speaker = word_speaker
append_speakerized_segment(speakerized_segments, current_words, segment)
continue
speakerized_segments.append(
{
"start": segment.get("start", 0),
"end": segment.get("end"),
"text": segment.get("text", "").strip(),
"speaker": get_speaker_for_interval(
segment.get("start", 0),
segment.get("end"),
diarization_turns,
),
}
)
return [segment for segment in speakerized_segments if segment.get("text")]
def split_text_into_chunks(text, target_chars, overlap_chars):
if len(text) <= target_chars:
return [text]
chunks = []
start = 0
text_length = len(text)
while start < text_length:
end = min(start + target_chars, text_length)
if end < text_length:
split_at = text.rfind("\n\n", start, end)
if split_at <= start:
split_at = text.rfind("\n", start, end)
if split_at <= start:
split_at = text.rfind(" ", start, end)
if split_at <= start:
split_at = end
else:
split_at = end
chunk = text[start:split_at].strip()
if chunk: