@clipen/clipen-cli 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +60 -50
  2. package/package.json +7 -4
  3. package/pyproject.toml +18 -2
  4. package/requirements/dev.txt +2 -0
  5. package/src/clipen/__init__.py +1 -1
  6. package/src/clipen/analysis/__init__.py +7 -7
  7. package/src/clipen/analysis/artifacts.py +4 -10
  8. package/src/clipen/analysis/audio.py +10 -8
  9. package/src/clipen/analysis/evidence_service.py +345 -167
  10. package/src/clipen/analysis/image_similarity.py +5 -14
  11. package/src/clipen/analysis/keyframes.py +5 -17
  12. package/src/clipen/analysis/models.py +5 -7
  13. package/src/clipen/analysis/qwen_worker.py +19 -54
  14. package/src/clipen/analysis/resources.py +2 -1
  15. package/src/clipen/analysis/runtime.py +1 -3
  16. package/src/clipen/analysis/service.py +16 -48
  17. package/src/clipen/analysis/setup.py +11 -25
  18. package/src/clipen/analysis/setup_cli.py +5 -15
  19. package/src/clipen/analysis/storage.py +96 -278
  20. package/src/clipen/analysis/transcription.py +40 -82
  21. package/src/clipen/analysis/visual.py +109 -48
  22. package/src/clipen/annotations/__init__.py +5 -2
  23. package/src/clipen/annotations/models.py +1 -1
  24. package/src/clipen/annotations/storage.py +132 -84
  25. package/src/clipen/annotations/suggestions.py +3 -8
  26. package/src/clipen/asr_release.py +4 -11
  27. package/src/clipen/bootstrap.py +65 -54
  28. package/src/clipen/{planning/models.py → candidates.py} +29 -47
  29. package/src/clipen/cli.py +2 -2
  30. package/src/clipen/controller/app.py +401 -214
  31. package/src/clipen/controller/server.py +28 -38
  32. package/src/clipen/domain/__init__.py +1 -1
  33. package/src/clipen/domain/media_time.py +3 -10
  34. package/src/clipen/domain/timeline.py +45 -47
  35. package/src/clipen/domain/validation.py +0 -1
  36. package/src/clipen/editing/__init__.py +1 -1
  37. package/src/clipen/editing/agent_models.py +4 -11
  38. package/src/clipen/editing/agent_repository.py +391 -170
  39. package/src/clipen/editing/agent_tools.py +180 -99
  40. package/src/clipen/editing/alignment.py +92 -52
  41. package/src/clipen/editing/alignment_setup.py +118 -70
  42. package/src/clipen/editing/alignment_worker.py +11 -9
  43. package/src/clipen/editing/change_report.py +95 -38
  44. package/src/clipen/editing/compiler.py +0 -1
  45. package/src/clipen/editing/component_looks.py +58 -34
  46. package/src/clipen/editing/component_review.py +34 -38
  47. package/src/clipen/editing/coordinator.py +213 -90
  48. package/src/clipen/editing/editorial_review.py +217 -95
  49. package/src/clipen/editing/evidence_jobs.py +457 -200
  50. package/src/clipen/editing/history_changes.py +129 -68
  51. package/src/clipen/editing/music_choices.py +8 -5
  52. package/src/clipen/editing/production_catalog.py +573 -136
  53. package/src/clipen/editing/production_limits.py +43 -17
  54. package/src/clipen/editing/production_media.py +376 -167
  55. package/src/clipen/editing/production_preview.py +322 -129
  56. package/src/clipen/editing/production_progress.py +164 -69
  57. package/src/clipen/editing/production_requirements.py +106 -39
  58. package/src/clipen/editing/production_tools.py +1064 -462
  59. package/src/clipen/editing/program_audio.py +211 -81
  60. package/src/clipen/editing/program_direction.py +59 -25
  61. package/src/clipen/editing/program_story.py +83 -45
  62. package/src/clipen/editing/program_subtitles.py +194 -96
  63. package/src/clipen/editing/programme_review.py +98 -50
  64. package/src/clipen/editing/prompt_history.py +64 -27
  65. package/src/clipen/editing/recut.py +65 -25
  66. package/src/clipen/editing/refinement_references.py +176 -86
  67. package/src/clipen/editing/resolve_export.py +449 -218
  68. package/src/clipen/editing/resolve_titles.py +162 -105
  69. package/src/clipen/editing/skill_tools.py +530 -154
  70. package/src/clipen/editing/source_dialogue.py +177 -67
  71. package/src/clipen/editing/speech_coverage.py +42 -22
  72. package/src/clipen/editing/speech_quality.py +6 -1
  73. package/src/clipen/editing/tool_receipts.py +78 -32
  74. package/src/clipen/editing/versions.py +122 -64
  75. package/src/clipen/editing/visual_preview.py +157 -61
  76. package/src/clipen/editing/workbench.py +104 -42
  77. package/src/clipen/finishing/audio.py +69 -30
  78. package/src/clipen/finishing/catalog.py +176 -93
  79. package/src/clipen/finishing/models.py +1 -1
  80. package/src/clipen/finishing/renderer.py +33 -14
  81. package/src/clipen/mcp_editing/__main__.py +3 -1
  82. package/src/clipen/mcp_editing/server.py +77 -34
  83. package/src/clipen/media/__init__.py +3 -3
  84. package/src/clipen/media/discovery.py +7 -20
  85. package/src/clipen/media/models.py +7 -18
  86. package/src/clipen/media/preview.py +14 -24
  87. package/src/clipen/media/probe.py +16 -44
  88. package/src/clipen/media/service.py +6 -19
  89. package/src/clipen/media/storage.py +33 -81
  90. package/src/clipen/music_vocabulary.py +33 -4
  91. package/src/clipen/power.py +8 -3
  92. package/src/clipen/projects/__init__.py +1 -1
  93. package/src/clipen/projects/deletion.py +19 -32
  94. package/src/clipen/projects/finishing_schema.py +3 -1
  95. package/src/clipen/projects/models.py +2 -5
  96. package/src/clipen/projects/picker.py +13 -37
  97. package/src/clipen/projects/service.py +8 -24
  98. package/src/clipen/projects/storage.py +226 -246
  99. package/src/clipen/provider_registry.py +4 -2
  100. package/src/clipen/providers/account.py +86 -35
  101. package/src/clipen/providers/claude.py +59 -25
  102. package/src/clipen/providers/claude_editing.py +14 -7
  103. package/src/clipen/providers/codex.py +73 -118
  104. package/src/clipen/providers/codex_editing.py +2 -2
  105. package/src/clipen/providers/editing_agent.py +19 -17
  106. package/src/clipen/providers/recovery.py +7 -8
  107. package/src/clipen/rendering/cover.py +18 -5
  108. package/src/clipen/rendering/custom_components.py +167 -79
  109. package/src/clipen/rendering/custom_render.py +62 -41
  110. package/src/clipen/rendering/production_effects.py +77 -45
  111. package/src/clipen/rendering/program_components.py +134 -73
  112. package/src/clipen/rendering/program_creator.py +432 -277
  113. package/src/clipen/rendering/program_identities.py +277 -182
  114. package/src/clipen/rendering/program_motion.py +140 -95
  115. package/src/clipen/rendering/program_studio.py +175 -116
  116. package/src/clipen/rendering/program_styles.py +231 -145
  117. package/src/clipen/rendering/program_subtitles.py +71 -34
  118. package/src/clipen/rendering/renderer.py +150 -121
  119. package/src/clipen/rendering/storage.py +9 -22
  120. package/src/clipen/rendering/titles.py +193 -86
  121. package/src/clipen/skills/__init__.py +1 -0
  122. package/src/clipen/skills/catalog.py +151 -55
  123. package/src/clipen/skills/library.py +13 -7
  124. package/src/clipen/skills/package.py +46 -23
  125. package/src/clipen/skills/visual_styles.py +29 -18
  126. package/src/clipen/workspace.py +15 -44
  127. package/src/clipen/planning/__init__.py +0 -9
@@ -2,14 +2,14 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from dataclasses import dataclass
6
- from fractions import Fraction
7
5
  import hashlib
8
6
  import json
9
7
  import os
10
8
  import re
11
9
  import sqlite3
12
- from typing import Mapping, Any
10
+ from dataclasses import dataclass
11
+ from fractions import Fraction
12
+ from typing import Any, Mapping
13
13
 
14
14
  from clipen.annotations.suggestions import annotation_suggestions
15
15
  from clipen.media import InventoryRoot
@@ -35,7 +35,6 @@ from .models import (
35
35
  )
36
36
  from .transcription import TranscriptionResult
37
37
 
38
-
39
38
  _TERMINAL_STATES = frozenset(
40
39
  {
41
40
  PreparationState.SUCCEEDED,
@@ -120,18 +119,9 @@ class PreparationScope:
120
119
  raise ValueError("preparation estimate is invalid")
121
120
 
122
121
  def to_public(self) -> dict[str, object]:
123
- pending = sum(
124
- target.initial_status is PreparationItemStatus.PENDING
125
- for target in self.targets
126
- )
127
- no_audio = sum(
128
- target.initial_status is PreparationItemStatus.NO_AUDIO
129
- for target in self.targets
130
- )
131
- issues = sum(
132
- target.initial_status is PreparationItemStatus.FAILED
133
- for target in self.targets
134
- )
122
+ pending = sum(target.initial_status is PreparationItemStatus.PENDING for target in self.targets)
123
+ no_audio = sum(target.initial_status is PreparationItemStatus.NO_AUDIO for target in self.targets)
124
+ issues = sum(target.initial_status is PreparationItemStatus.FAILED for target in self.targets)
135
125
  return {
136
126
  "scope_id": self.scope_id,
137
127
  "inventory_run_id": self.inventory_run_id,
@@ -184,9 +174,7 @@ class PreparationRepository:
184
174
  def preflight(self, project_id: str) -> PreparationScope:
185
175
  validate_project_id(project_id)
186
176
  with self.projects.connect(project_id) as connection:
187
- project = connection.execute(
188
- "SELECT revision FROM project WHERE project_id = ?", (project_id,)
189
- ).fetchone()
177
+ project = connection.execute("SELECT revision FROM project WHERE project_id = ?", (project_id,)).fetchone()
190
178
  current = connection.execute(
191
179
  "SELECT i.run_id, r.roots_json FROM current_inventory i "
192
180
  "JOIN inventory_runs r ON r.run_id = i.run_id WHERE i.slot = 1"
@@ -201,16 +189,9 @@ class PreparationRepository:
201
189
  )
202
190
  try:
203
191
  raw_roots = json.loads(current["roots_json"])
204
- roots = {
205
- root.role: root
206
- for root in (
207
- InventoryRoot.from_storage(value) for value in raw_roots
208
- )
209
- }
192
+ roots = {root.role: root for root in (InventoryRoot.from_storage(value) for value in raw_roots)}
210
193
  except (json.JSONDecodeError, TypeError, ValueError, KeyError) as error:
211
- raise ProjectError(
212
- "storage_corrupt", "Clipen 無法讀取素材範圍。", status_code=500
213
- ) from error
194
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取素材範圍。", status_code=500) from error
214
195
  for root in roots.values():
215
196
  _verify_inventory_root(root)
216
197
  rows = connection.execute(
@@ -237,9 +218,7 @@ class PreparationRepository:
237
218
  role = DirectoryRole(row["role"])
238
219
  root = roots.get(role)
239
220
  if root is None:
240
- raise ProjectError(
241
- "storage_corrupt", "Clipen 無法讀取素材範圍。", status_code=500
242
- )
221
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取素材範圍。", status_code=500)
243
222
  if row["stream_index"] is None:
244
223
  if row["version_id"] not in seen_no_audio:
245
224
  seen_no_audio.add(row["version_id"])
@@ -257,9 +236,7 @@ class PreparationRepository:
257
236
  continue
258
237
  try:
259
238
  details = json.loads(row["details_json"])
260
- span = _source_span(
261
- row["version_id"], row["stream_index"], details
262
- )
239
+ span = _source_span(row["version_id"], row["stream_index"], details)
263
240
  audio = AudioPreparationInput(
264
241
  root,
265
242
  row["relative_path"],
@@ -270,9 +247,7 @@ class PreparationRepository:
270
247
  row["fingerprint"],
271
248
  span,
272
249
  )
273
- duration += Fraction(span.duration_pts) * Fraction(
274
- span.time_base.numerator, span.time_base.denominator
275
- )
250
+ duration += Fraction(span.duration_pts) * Fraction(span.time_base.numerator, span.time_base.denominator)
276
251
  targets.append(
277
252
  PreparationTarget(
278
253
  row["version_id"],
@@ -353,15 +328,11 @@ class PreparationRepository:
353
328
  # later project edit or inventory refresh.
354
329
  with self.projects.connect(project_id) as connection:
355
330
  receipt = connection.execute(
356
- "SELECT command_type, request_hash, run_id "
357
- "FROM preparation_command_receipts WHERE request_id = ?",
331
+ "SELECT command_type, request_hash, run_id FROM preparation_command_receipts WHERE request_id = ?",
358
332
  (normalized_request,),
359
333
  ).fetchone()
360
334
  if receipt is not None:
361
- if (
362
- receipt["command_type"] != "start_preparation"
363
- or receipt["request_hash"] != request_hash
364
- ):
335
+ if receipt["command_type"] != "start_preparation" or receipt["request_hash"] != request_hash:
365
336
  raise ProjectError(
366
337
  "request_reused",
367
338
  "這次操作的識別資訊已用於不同內容。",
@@ -394,15 +365,11 @@ class PreparationRepository:
394
365
  try:
395
366
  connection.execute("BEGIN IMMEDIATE")
396
367
  receipt = connection.execute(
397
- "SELECT command_type, request_hash, run_id "
398
- "FROM preparation_command_receipts WHERE request_id = ?",
368
+ "SELECT command_type, request_hash, run_id FROM preparation_command_receipts WHERE request_id = ?",
399
369
  (normalized_request,),
400
370
  ).fetchone()
401
371
  if receipt is not None:
402
- if (
403
- receipt["command_type"] != "start_preparation"
404
- or receipt["request_hash"] != request_hash
405
- ):
372
+ if receipt["command_type"] != "start_preparation" or receipt["request_hash"] != request_hash:
406
373
  raise ProjectError(
407
374
  "request_reused",
408
375
  "這次操作的識別資訊已用於不同內容。",
@@ -428,8 +395,7 @@ class PreparationRepository:
428
395
  status_code=409,
429
396
  )
430
397
  busy = connection.execute(
431
- "SELECT run_id FROM preparation_runs "
432
- "WHERE state IN ('queued', 'running', 'cancelling') LIMIT 1"
398
+ "SELECT run_id FROM preparation_runs WHERE state IN ('queued', 'running', 'cancelling') LIMIT 1"
433
399
  ).fetchone()
434
400
  if busy is not None:
435
401
  raise ProjectError(
@@ -440,13 +406,9 @@ class PreparationRepository:
440
406
  retired_artifact_paths = self._remove_previous_analysis(connection)
441
407
  now = utc_now()
442
408
  initial_no_audio = sum(
443
- target.initial_status is PreparationItemStatus.NO_AUDIO
444
- for target in scope.targets
445
- )
446
- initial_issues = sum(
447
- target.initial_status is PreparationItemStatus.FAILED
448
- for target in scope.targets
409
+ target.initial_status is PreparationItemStatus.NO_AUDIO for target in scope.targets
449
410
  )
411
+ initial_issues = sum(target.initial_status is PreparationItemStatus.FAILED for target in scope.targets)
450
412
  connection.execute(
451
413
  "INSERT INTO preparation_runs "
452
414
  "(run_id, project_id, request_id, project_revision, inventory_run_id, "
@@ -507,9 +469,7 @@ class PreparationRepository:
507
469
  raise
508
470
  except sqlite3.Error as error:
509
471
  connection.rollback()
510
- raise ProjectError(
511
- "storage_failed", "Clipen 無法建立素材分析。", status_code=500
512
- ) from error
472
+ raise ProjectError("storage_failed", "Clipen 無法建立素材分析。", status_code=500) from error
513
473
 
514
474
  @staticmethod
515
475
  def _remove_previous_analysis(connection: sqlite3.Connection) -> tuple[str, ...]:
@@ -534,8 +494,7 @@ class PreparationRepository:
534
494
  connection.execute("DELETE FROM transcription_revisions")
535
495
  connection.execute("DELETE FROM preparation_command_receipts")
536
496
  connection.execute(
537
- "DELETE FROM operation_events WHERE operation_id IN "
538
- "(SELECT operation_id FROM preparation_runs)"
497
+ "DELETE FROM operation_events WHERE operation_id IN (SELECT operation_id FROM preparation_runs)"
539
498
  )
540
499
  # Keep any record that another feature has explicitly adopted. This is
541
500
  # defensive today and prevents future evidence/export references from being
@@ -564,36 +523,26 @@ class PreparationRepository:
564
523
  with self.projects.connect(project_id) as connection:
565
524
  run = self._read_run(connection, run_id)
566
525
  if run.project_id != project_id:
567
- raise ProjectError(
568
- "preparation_not_found", "找不到這次素材分析。", status_code=404
569
- )
570
- row = connection.execute(
571
- "SELECT recipe_json FROM preparation_runs WHERE run_id = ?", (run_id,)
572
- ).fetchone()
526
+ raise ProjectError("preparation_not_found", "找不到這次素材分析。", status_code=404)
527
+ row = connection.execute("SELECT recipe_json FROM preparation_runs WHERE run_id = ?", (run_id,)).fetchone()
573
528
  try:
574
529
  value = json.loads(row["recipe_json"])
575
530
  if not isinstance(value, dict):
576
531
  raise ValueError("recipe is not an object")
577
532
  return value
578
533
  except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
579
- raise ProjectError(
580
- "storage_corrupt", "Clipen 無法讀取分析設定。", status_code=500
581
- ) from error
534
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取分析設定。", status_code=500) from error
582
535
 
583
536
  def latest_run(self, project_id: str) -> PreparationRun | None:
584
537
  validate_project_id(project_id)
585
538
  with self.projects.connect(project_id) as connection:
586
- row = connection.execute(
587
- "SELECT run_id FROM preparation_runs ORDER BY created_at DESC LIMIT 1"
588
- ).fetchone()
539
+ row = connection.execute("SELECT run_id FROM preparation_runs ORDER BY created_at DESC LIMIT 1").fetchone()
589
540
  return None if row is None else self._read_run(connection, row["run_id"])
590
541
 
591
542
  def current_run(self, project_id: str) -> PreparationRun | None:
592
543
  validate_project_id(project_id)
593
544
  with self.projects.connect(project_id) as connection:
594
- row = connection.execute(
595
- "SELECT run_id FROM current_preparation WHERE slot = 1"
596
- ).fetchone()
545
+ row = connection.execute("SELECT run_id FROM current_preparation WHERE slot = 1").fetchone()
597
546
  return None if row is None else self._read_run(connection, row["run_id"])
598
547
 
599
548
  def result_items(
@@ -618,9 +567,7 @@ class PreparationRepository:
618
567
  with self.projects.connect(project_id) as connection:
619
568
  run = self._read_run(connection, run_id)
620
569
  if run.project_id != project_id:
621
- raise ProjectError(
622
- "preparation_not_found", "找不到這次素材分析。", status_code=404
623
- )
570
+ raise ProjectError("preparation_not_found", "找不到這次素材分析。", status_code=404)
624
571
  suggestions = annotation_suggestions(connection)
625
572
  material_rows = {
626
573
  row["version_id"]: row
@@ -633,8 +580,7 @@ class PreparationRepository:
633
580
  ).fetchall()
634
581
  }
635
582
  version_counts = connection.execute(
636
- "SELECT version_id,COUNT(*) AS item_count FROM preparation_items "
637
- "WHERE run_id=? GROUP BY version_id",
583
+ "SELECT version_id,COUNT(*) AS item_count FROM preparation_items WHERE run_id=? GROUP BY version_id",
638
584
  (run_id,),
639
585
  ).fetchall()
640
586
  effective_days: dict[str, int | None] = {}
@@ -650,13 +596,9 @@ class PreparationRepository:
650
596
  where = ["pi.run_id = ?"]
651
597
  parameters: list[object] = [run_id]
652
598
  if trip_day is not None:
653
- matching_versions = [
654
- version_id for version_id, day in effective_days.items() if day == trip_day
655
- ]
599
+ matching_versions = [version_id for version_id, day in effective_days.items() if day == trip_day]
656
600
  if matching_versions:
657
- where.append(
658
- f"pi.version_id IN ({','.join('?' for _ in matching_versions)})"
659
- )
601
+ where.append(f"pi.version_id IN ({','.join('?' for _ in matching_versions)})")
660
602
  parameters.extend(matching_versions)
661
603
  else:
662
604
  where.append("0 = 1")
@@ -670,8 +612,7 @@ class PreparationRepository:
670
612
  " AND ta.stream_index=pi.stream_index "
671
613
  )
672
614
  total = connection.execute(
673
- "SELECT COUNT(*) FROM preparation_items pi" + joins
674
- + " WHERE " + " AND ".join(where),
615
+ "SELECT COUNT(*) FROM preparation_items pi" + joins + " WHERE " + " AND ".join(where),
675
616
  parameters,
676
617
  ).fetchone()[0]
677
618
  rows = connection.execute(
@@ -698,9 +639,7 @@ class PreparationRepository:
698
639
  "JOIN inventory_items ii ON ii.run_id = pr.inventory_run_id "
699
640
  " AND ii.asset_id = a.asset_id "
700
641
  "LEFT JOIN transcription_revisions tr "
701
- " ON tr.revision_id = pi.transcript_revision_id "
702
- + joins
703
- + "WHERE " + " AND ".join(where) + " "
642
+ " ON tr.revision_id = pi.transcript_revision_id " + joins + "WHERE " + " AND ".join(where) + " "
704
643
  "ORDER BY ii.display_name COLLATE NOCASE, pi.stream_index "
705
644
  "LIMIT ? OFFSET ?",
706
645
  (*parameters, limit, offset),
@@ -721,28 +660,21 @@ class PreparationRepository:
721
660
  raise ValueError("transcript preview is invalid")
722
661
  public_status = (
723
662
  "needs_review"
724
- if row["status"] == PreparationItemStatus.TRANSCRIBED.value
725
- and row["review_required"] == 1
663
+ if row["status"] == PreparationItemStatus.TRANSCRIBED.value and row["review_required"] == 1
726
664
  else PreparationItemStatus(row["status"]).value
727
665
  )
728
666
  suggestion = suggestions.get(row["version_id"], {})
729
667
  effective_day = (
730
- row["annotated_trip_day"]
731
- if row["material_revision"] is not None
732
- else suggestion.get("trip_day")
668
+ row["annotated_trip_day"] if row["material_revision"] is not None else suggestion.get("trip_day")
733
669
  )
734
670
  effective_day_part = (
735
- row["annotated_day_part"]
736
- if row["material_revision"] is not None
737
- else suggestion.get("day_part")
671
+ row["annotated_day_part"] if row["material_revision"] is not None else suggestion.get("day_part")
738
672
  )
739
673
  transcript_confirmed = (
740
674
  row["transcript_confirmed"] == 1
741
675
  and row["annotation_source_revision"] == row["transcript_revision_id"]
742
676
  )
743
- transcript_discarded = (
744
- row["transcript_discarded"] == 1
745
- )
677
+ transcript_discarded = row["transcript_discarded"] == 1
746
678
  if row["usage"] == "exclude":
747
679
  user_state = "excluded"
748
680
  elif row["usage"] == "must_use":
@@ -765,13 +697,9 @@ class PreparationRepository:
765
697
  "language": row["language"],
766
698
  "source": source,
767
699
  "segment_count": row["segment_count"],
768
- "preview_text": (
769
- None if preview is None or transcript_discarded else preview[:280]
770
- ),
700
+ "preview_text": (None if preview is None or transcript_discarded else preview[:280]),
771
701
  "preview_start_pts": row["preview_start_pts"],
772
- "preview_truncated": (
773
- not transcript_discarded and preview is not None and len(preview) > 280
774
- ),
702
+ "preview_truncated": (not transcript_discarded and preview is not None and len(preview) > 280),
775
703
  "transcript_discarded": transcript_discarded,
776
704
  "user_state": user_state,
777
705
  "trip_day": effective_day,
@@ -786,18 +714,13 @@ class PreparationRepository:
786
714
  "limit": limit,
787
715
  "next_offset": offset + len(items) if offset + len(items) < total else None,
788
716
  "filters": {
789
- "trip_days": [
790
- {"day": day, "count": count}
791
- for day, count in sorted(day_counts.items())
792
- ],
717
+ "trip_days": [{"day": day, "count": count} for day, count in sorted(day_counts.items())],
793
718
  "review_state": review_state,
794
719
  "trip_day": trip_day,
795
720
  },
796
721
  }
797
722
  except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
798
- raise ProjectError(
799
- "storage_corrupt", "Clipen 無法讀取逐字稿清單。", status_code=500
800
- ) from error
723
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取逐字稿清單。", status_code=500) from error
801
724
 
802
725
  def transcript_segments(
803
726
  self,
@@ -813,19 +736,13 @@ class PreparationRepository:
813
736
  validate_project_id(project_id)
814
737
  self._validate_result_page(offset, limit)
815
738
  if re.fullmatch(r"av_[0-9a-f]{32}", version_id) is None:
816
- raise ProjectError(
817
- "transcript_not_found", "找不到這份逐字稿。", status_code=404
818
- )
739
+ raise ProjectError("transcript_not_found", "找不到這份逐字稿。", status_code=404)
819
740
  if isinstance(stream_index, bool) or not isinstance(stream_index, int) or stream_index < 0:
820
- raise ProjectError(
821
- "transcript_not_found", "找不到這份逐字稿。", status_code=404
822
- )
741
+ raise ProjectError("transcript_not_found", "找不到這份逐字稿。", status_code=404)
823
742
  with self.projects.connect(project_id) as connection:
824
743
  run = self._read_run(connection, run_id)
825
744
  if run.project_id != project_id:
826
- raise ProjectError(
827
- "preparation_not_found", "找不到這次素材分析。", status_code=404
828
- )
745
+ raise ProjectError("preparation_not_found", "找不到這次素材分析。", status_code=404)
829
746
  item = connection.execute(
830
747
  "SELECT pi.status, pi.transcript_revision_id, ii.display_name, a.role, "
831
748
  "tr.language, tr.source_span_json "
@@ -841,14 +758,10 @@ class PreparationRepository:
841
758
  (run_id, version_id, stream_index),
842
759
  ).fetchone()
843
760
  if item is None:
844
- raise ProjectError(
845
- "transcript_not_found", "找不到這份逐字稿。", status_code=404
846
- )
761
+ raise ProjectError("transcript_not_found", "找不到這份逐字稿。", status_code=404)
847
762
  revision_id = item["transcript_revision_id"]
848
763
  if revision_id is None or item["status"] != PreparationItemStatus.TRANSCRIBED.value:
849
- raise ProjectError(
850
- "transcript_unavailable", "這個素材沒有可查看的逐字稿。", status_code=409
851
- )
764
+ raise ProjectError("transcript_unavailable", "這個素材沒有可查看的逐字稿。", status_code=409)
852
765
  total = connection.execute(
853
766
  "SELECT COUNT(*) FROM transcript_segments WHERE revision_id = ?",
854
767
  (revision_id,),
@@ -896,9 +809,7 @@ class PreparationRepository:
896
809
  "next_offset": offset + len(segments) if offset + len(segments) < total else None,
897
810
  }
898
811
  except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
899
- raise ProjectError(
900
- "storage_corrupt", "Clipen 無法讀取逐字稿內容。", status_code=500
901
- ) from error
812
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取逐字稿內容。", status_code=500) from error
902
813
 
903
814
  @staticmethod
904
815
  def _validate_result_page(offset: int, limit: int) -> None:
@@ -934,9 +845,7 @@ class PreparationRepository:
934
845
  with self.projects.connect(project_id) as connection:
935
846
  run = self._read_run(connection, run_id)
936
847
  if run.project_id != project_id:
937
- raise ProjectError(
938
- "preparation_not_found", "找不到這次素材分析。", status_code=404
939
- )
848
+ raise ProjectError("preparation_not_found", "找不到這次素材分析。", status_code=404)
940
849
  rows = connection.execute(
941
850
  "SELECT sequence, event_type, payload_json, created_at "
942
851
  "FROM operation_events WHERE project_id = ? AND operation_id = ? "
@@ -958,14 +867,10 @@ class PreparationRepository:
958
867
  }
959
868
  )
960
869
  except (json.JSONDecodeError, TypeError, ValueError) as error:
961
- raise ProjectError(
962
- "storage_corrupt", "Clipen 無法讀取分析進度。", status_code=500
963
- ) from error
870
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取分析進度。", status_code=500) from error
964
871
  return tuple(events)
965
872
 
966
- def list_work_items(
967
- self, project_id: str, run_id: str
968
- ) -> tuple[PreparationWorkItem, ...]:
873
+ def list_work_items(self, project_id: str, run_id: str) -> tuple[PreparationWorkItem, ...]:
969
874
  run = self.get_run(project_id, run_id)
970
875
  scope = self.preflight(project_id)
971
876
  if scope.scope_id != run.scope_id or scope.inventory_run_id != run.inventory_run_id:
@@ -974,9 +879,7 @@ class PreparationRepository:
974
879
  "素材或作品內容已改變,無法繼續這次分析。",
975
880
  status_code=409,
976
881
  )
977
- targets = {
978
- (target.version_id, target.stream_index): target for target in scope.targets
979
- }
882
+ targets = {(target.version_id, target.stream_index): target for target in scope.targets}
980
883
  with self.projects.connect(project_id) as connection:
981
884
  rows = connection.execute(
982
885
  "SELECT version_id, stream_index, status, audio_artifact_id, "
@@ -996,9 +899,7 @@ class PreparationRepository:
996
899
  for row in rows
997
900
  )
998
901
  except (KeyError, TypeError, ValueError) as error:
999
- raise ProjectError(
1000
- "storage_corrupt", "Clipen 無法讀取分析項目。", status_code=500
1001
- ) from error
902
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取分析項目。", status_code=500) from error
1002
903
 
1003
904
  def register_chunks(
1004
905
  self,
@@ -1021,8 +922,7 @@ class PreparationRepository:
1021
922
  status_code=409,
1022
923
  )
1023
924
  item = connection.execute(
1024
- "SELECT status FROM preparation_items WHERE run_id = ? "
1025
- "AND version_id = ? AND stream_index = ?",
925
+ "SELECT status FROM preparation_items WHERE run_id = ? AND version_id = ? AND stream_index = ?",
1026
926
  (run_id, version_id, stream_index),
1027
927
  ).fetchone()
1028
928
  if item is None or item["status"] != PreparationItemStatus.PREPARED.value:
@@ -1040,8 +940,7 @@ class PreparationRepository:
1040
940
  ).fetchall()
1041
941
  if existing:
1042
942
  observed = tuple(
1043
- (row["start_sample"], row["end_sample"], row["source_span_json"])
1044
- for row in existing
943
+ (row["start_sample"], row["end_sample"], row["source_span_json"]) for row in existing
1045
944
  )
1046
945
  requested = tuple(
1047
946
  (
@@ -1097,9 +996,7 @@ class PreparationRepository:
1097
996
  raise
1098
997
  except sqlite3.Error as error:
1099
998
  connection.rollback()
1100
- raise ProjectError(
1101
- "storage_failed", "Clipen 無法保存音訊切塊。", status_code=500
1102
- ) from error
999
+ raise ProjectError("storage_failed", "Clipen 無法保存音訊切塊。", status_code=500) from error
1103
1000
 
1104
1001
  def settle_chunk(
1105
1002
  self,
@@ -1111,11 +1008,7 @@ class PreparationRepository:
1111
1008
  artifact_id: str,
1112
1009
  result: TranscriptionResult,
1113
1010
  ) -> PreparationChunk:
1114
- status = (
1115
- PreparationChunkStatus.NO_SPEECH
1116
- if result.no_speech_detected
1117
- else PreparationChunkStatus.TRANSCRIBED
1118
- )
1011
+ status = PreparationChunkStatus.NO_SPEECH if result.no_speech_detected else PreparationChunkStatus.TRANSCRIBED
1119
1012
  result_json = _encoded_json(result.to_storage(), "transcript result", 32 * 1024 * 1024)
1120
1013
  with self.projects.connect(project_id) as connection:
1121
1014
  try:
@@ -1134,9 +1027,7 @@ class PreparationRepository:
1134
1027
  (run_id, version_id, stream_index, ordinal),
1135
1028
  ).fetchone()
1136
1029
  if row is None:
1137
- raise ProjectError(
1138
- "preparation_chunk_not_found", "找不到這個音訊切塊。", status_code=404
1139
- )
1030
+ raise ProjectError("preparation_chunk_not_found", "找不到這個音訊切塊。", status_code=404)
1140
1031
  if row["status"] != PreparationChunkStatus.PENDING.value:
1141
1032
  completed = self._read_chunk(row)
1142
1033
  if completed.transcript_artifact_id != artifact_id or completed.result != result:
@@ -1175,9 +1066,7 @@ class PreparationRepository:
1175
1066
  raise
1176
1067
  except sqlite3.Error as error:
1177
1068
  connection.rollback()
1178
- raise ProjectError(
1179
- "storage_failed", "Clipen 無法保存逐字稿切塊。", status_code=500
1180
- ) from error
1069
+ raise ProjectError("storage_failed", "Clipen 無法保存逐字稿切塊。", status_code=500) from error
1181
1070
 
1182
1071
  def publish_transcript_revision(
1183
1072
  self,
@@ -1199,17 +1088,14 @@ class PreparationRepository:
1199
1088
  if not re.fullmatch(r"[a-z][a-z0-9_.-]{0,127}", recipe_id):
1200
1089
  raise ValueError("transcript recipe is invalid")
1201
1090
  if any(
1202
- segment.source_span.version_id != version_id
1203
- or segment.source_span.stream_index != stream_index
1091
+ segment.source_span.version_id != version_id or segment.source_span.stream_index != stream_index
1204
1092
  for segment in segments
1205
1093
  ):
1206
1094
  raise ValueError("timeline segment belongs to another source")
1207
1095
  if not isinstance(needs_review, bool) or (needs_review and not segments):
1208
1096
  raise ValueError("transcript review status is invalid")
1209
1097
  model_json = _bounded_json(model, "ASR model")
1210
- source_json = json.dumps(
1211
- source_span.to_storage(), sort_keys=True, separators=(",", ":")
1212
- )
1098
+ source_json = json.dumps(source_span.to_storage(), sort_keys=True, separators=(",", ":"))
1213
1099
  identity = {
1214
1100
  "run_id": run_id,
1215
1101
  "version_id": version_id,
@@ -1219,9 +1105,10 @@ class PreparationRepository:
1219
1105
  "recipe_id": recipe_id,
1220
1106
  "needs_review": needs_review,
1221
1107
  }
1222
- revision_id = "trn_" + hashlib.sha256(
1223
- json.dumps(identity, sort_keys=True, separators=(",", ":")).encode()
1224
- ).hexdigest()[:32]
1108
+ revision_id = (
1109
+ "trn_"
1110
+ + hashlib.sha256(json.dumps(identity, sort_keys=True, separators=(",", ":")).encode()).hexdigest()[:32]
1111
+ )
1225
1112
  with self.projects.connect(project_id) as connection:
1226
1113
  try:
1227
1114
  connection.execute("BEGIN IMMEDIATE")
@@ -1238,9 +1125,7 @@ class PreparationRepository:
1238
1125
  (run_id, version_id, stream_index),
1239
1126
  ).fetchone()
1240
1127
  if item is None:
1241
- raise ProjectError(
1242
- "preparation_item_not_found", "找不到這個分析項目。", status_code=404
1243
- )
1128
+ raise ProjectError("preparation_item_not_found", "找不到這個分析項目。", status_code=404)
1244
1129
  if item["transcript_revision_id"] is not None:
1245
1130
  if item["transcript_revision_id"] != revision_id:
1246
1131
  raise ProjectError(
@@ -1269,8 +1154,7 @@ class PreparationRepository:
1269
1154
  status_code=409,
1270
1155
  )
1271
1156
  artifact = connection.execute(
1272
- "SELECT project_id, kind, producer_operation_id FROM artifacts "
1273
- "WHERE artifact_id = ?",
1157
+ "SELECT project_id, kind, producer_operation_id FROM artifacts WHERE artifact_id = ?",
1274
1158
  (artifact_id,),
1275
1159
  ).fetchone()
1276
1160
  if (
@@ -1279,14 +1163,8 @@ class PreparationRepository:
1279
1163
  or artifact["kind"] != "transcript"
1280
1164
  or artifact["producer_operation_id"] != run.operation_id
1281
1165
  ):
1282
- raise ProjectError(
1283
- "artifact_not_found", "找不到完整逐字稿成果。", status_code=409
1284
- )
1285
- status = (
1286
- "no_speech_detected"
1287
- if not segments
1288
- else "needs_review" if needs_review else "transcribed"
1289
- )
1166
+ raise ProjectError("artifact_not_found", "找不到完整逐字稿成果。", status_code=409)
1167
+ status = "no_speech_detected" if not segments else "needs_review" if needs_review else "transcribed"
1290
1168
  now = utc_now()
1291
1169
  connection.execute(
1292
1170
  "INSERT INTO transcription_revisions "
@@ -1313,9 +1191,7 @@ class PreparationRepository:
1313
1191
  f"{revision_id}\0{ordinal}\0{segment.source_span.start_pts}\0"
1314
1192
  f"{segment.source_span.end_pts}\0{segment.text}"
1315
1193
  )
1316
- segment_id = "seg_" + hashlib.sha256(
1317
- segment_identity.encode("utf-8")
1318
- ).hexdigest()[:32]
1194
+ segment_id = "seg_" + hashlib.sha256(segment_identity.encode("utf-8")).hexdigest()[:32]
1319
1195
  connection.execute(
1320
1196
  "INSERT INTO transcript_segments "
1321
1197
  "(revision_id, segment_id, start_pts, end_pts, text, confidence, ordinal) "
@@ -1330,11 +1206,7 @@ class PreparationRepository:
1330
1206
  ordinal,
1331
1207
  ),
1332
1208
  )
1333
- item_status = (
1334
- PreparationItemStatus.NO_SPEECH
1335
- if not segments
1336
- else PreparationItemStatus.TRANSCRIBED
1337
- )
1209
+ item_status = PreparationItemStatus.NO_SPEECH if not segments else PreparationItemStatus.TRANSCRIBED
1338
1210
  connection.execute(
1339
1211
  "UPDATE preparation_items SET status = ?, transcript_revision_id = ?, "
1340
1212
  "review_required = ?, error_code = ? "
@@ -1369,9 +1241,7 @@ class PreparationRepository:
1369
1241
  raise
1370
1242
  except sqlite3.Error as error:
1371
1243
  connection.rollback()
1372
- raise ProjectError(
1373
- "storage_failed", "Clipen 無法發布逐字稿。", status_code=500
1374
- ) from error
1244
+ raise ProjectError("storage_failed", "Clipen 無法發布逐字稿。", status_code=500) from error
1375
1245
 
1376
1246
  def transition(
1377
1247
  self,
@@ -1385,9 +1255,7 @@ class PreparationRepository:
1385
1255
  validate_project_id(project_id)
1386
1256
  if not re.fullmatch(r"[a-z][a-z0-9_]{0,63}", phase):
1387
1257
  raise ValueError("preparation phase is invalid")
1388
- if error_code is not None and not re.fullmatch(
1389
- r"[a-z][a-z0-9_]{0,63}", error_code
1390
- ):
1258
+ if error_code is not None and not re.fullmatch(r"[a-z][a-z0-9_]{0,63}", error_code):
1391
1259
  raise ValueError("preparation error code is invalid")
1392
1260
  if target is PreparationState.SUCCEEDED:
1393
1261
  raise ValueError("use publish() to complete a preparation")
@@ -1396,9 +1264,7 @@ class PreparationRepository:
1396
1264
  connection.execute("BEGIN IMMEDIATE")
1397
1265
  current = self._read_run(connection, run_id)
1398
1266
  if current.project_id != project_id:
1399
- raise ProjectError(
1400
- "preparation_not_found", "找不到這次素材分析。", status_code=404
1401
- )
1267
+ raise ProjectError("preparation_not_found", "找不到這次素材分析。", status_code=404)
1402
1268
  if target not in _TRANSITIONS.get(current.state, set()):
1403
1269
  raise ProjectError(
1404
1270
  "preparation_state_conflict",
@@ -1429,9 +1295,7 @@ class PreparationRepository:
1429
1295
  raise
1430
1296
  except sqlite3.Error as error:
1431
1297
  connection.rollback()
1432
- raise ProjectError(
1433
- "storage_failed", "Clipen 無法更新素材分析。", status_code=500
1434
- ) from error
1298
+ raise ProjectError("storage_failed", "Clipen 無法更新素材分析。", status_code=500) from error
1435
1299
 
1436
1300
  def request_cancel(self, project_id: str, run_id: str) -> PreparationRun:
1437
1301
  validate_project_id(project_id)
@@ -1440,9 +1304,7 @@ class PreparationRepository:
1440
1304
  connection.execute("BEGIN IMMEDIATE")
1441
1305
  current = self._read_run(connection, run_id)
1442
1306
  if current.project_id != project_id:
1443
- raise ProjectError(
1444
- "preparation_not_found", "找不到這次素材分析。", status_code=404
1445
- )
1307
+ raise ProjectError("preparation_not_found", "找不到這次素材分析。", status_code=404)
1446
1308
  if current.state in _TERMINAL_STATES or current.state is PreparationState.CANCELLING:
1447
1309
  connection.rollback()
1448
1310
  return current
@@ -1456,8 +1318,7 @@ class PreparationRepository:
1456
1318
  event_type = "cancelled"
1457
1319
  else:
1458
1320
  connection.execute(
1459
- "UPDATE preparation_runs SET state = 'cancelling', "
1460
- "phase = 'cancelling' WHERE run_id = ?",
1321
+ "UPDATE preparation_runs SET state = 'cancelling', phase = 'cancelling' WHERE run_id = ?",
1461
1322
  (run_id,),
1462
1323
  )
1463
1324
  event_type = "cancel_requested"
@@ -1477,27 +1338,19 @@ class PreparationRepository:
1477
1338
  raise
1478
1339
  except sqlite3.Error as error:
1479
1340
  connection.rollback()
1480
- raise ProjectError(
1481
- "storage_failed", "Clipen 無法取消素材分析。", status_code=500
1482
- ) from error
1341
+ raise ProjectError("storage_failed", "Clipen 無法取消素材分析。", status_code=500) from error
1483
1342
 
1484
- def resume_interrupted(
1485
- self, project_id: str, run_id: str, request_id: object
1486
- ) -> tuple[PreparationRun, bool]:
1343
+ def resume_interrupted(self, project_id: str, run_id: str, request_id: object) -> tuple[PreparationRun, bool]:
1487
1344
  validate_project_id(project_id)
1488
1345
  normalized_request = validate_request_id(request_id)
1489
1346
  request_hash = command_digest({"run_id": run_id})
1490
1347
  with self.projects.connect(project_id) as connection:
1491
1348
  receipt = connection.execute(
1492
- "SELECT command_type, request_hash, run_id "
1493
- "FROM preparation_command_receipts WHERE request_id = ?",
1349
+ "SELECT command_type, request_hash, run_id FROM preparation_command_receipts WHERE request_id = ?",
1494
1350
  (normalized_request,),
1495
1351
  ).fetchone()
1496
1352
  if receipt is not None:
1497
- if (
1498
- receipt["command_type"] != "resume_preparation"
1499
- or receipt["request_hash"] != request_hash
1500
- ):
1353
+ if receipt["command_type"] != "resume_preparation" or receipt["request_hash"] != request_hash:
1501
1354
  raise ProjectError(
1502
1355
  "request_reused",
1503
1356
  "這次操作的識別資訊已用於不同內容。",
@@ -1509,15 +1362,11 @@ class PreparationRepository:
1509
1362
  try:
1510
1363
  connection.execute("BEGIN IMMEDIATE")
1511
1364
  receipt = connection.execute(
1512
- "SELECT command_type, request_hash, run_id "
1513
- "FROM preparation_command_receipts WHERE request_id = ?",
1365
+ "SELECT command_type, request_hash, run_id FROM preparation_command_receipts WHERE request_id = ?",
1514
1366
  (normalized_request,),
1515
1367
  ).fetchone()
1516
1368
  if receipt is not None:
1517
- if (
1518
- receipt["command_type"] != "resume_preparation"
1519
- or receipt["request_hash"] != request_hash
1520
- ):
1369
+ if receipt["command_type"] != "resume_preparation" or receipt["request_hash"] != request_hash:
1521
1370
  raise ProjectError(
1522
1371
  "request_reused",
1523
1372
  "這次操作的識別資訊已用於不同內容。",
@@ -1528,9 +1377,7 @@ class PreparationRepository:
1528
1377
  return replay, False
1529
1378
  current = self._read_run(connection, run_id)
1530
1379
  if current.project_id != project_id:
1531
- raise ProjectError(
1532
- "preparation_not_found", "找不到這次素材分析。", status_code=404
1533
- )
1380
+ raise ProjectError("preparation_not_found", "找不到這次素材分析。", status_code=404)
1534
1381
  if current.state is not PreparationState.INTERRUPTED:
1535
1382
  raise ProjectError(
1536
1383
  "preparation_state_conflict",
@@ -1567,9 +1414,7 @@ class PreparationRepository:
1567
1414
  status_code=409,
1568
1415
  )
1569
1416
  attempt_number = current.attempt_number + 1
1570
- attempt_id = _derived_id(
1571
- "att", current.operation_id, str(attempt_number)
1572
- )
1417
+ attempt_id = _derived_id("att", current.operation_id, str(attempt_number))
1573
1418
  now = utc_now()
1574
1419
  connection.execute(
1575
1420
  "UPDATE preparation_runs SET attempt_id = ?, attempt_number = ?, "
@@ -1599,9 +1444,7 @@ class PreparationRepository:
1599
1444
  raise
1600
1445
  except sqlite3.Error as error:
1601
1446
  connection.rollback()
1602
- raise ProjectError(
1603
- "storage_failed", "Clipen 無法接續素材分析。", status_code=500
1604
- ) from error
1447
+ raise ProjectError("storage_failed", "Clipen 無法接續素材分析。", status_code=500) from error
1605
1448
 
1606
1449
  def settle_item(
1607
1450
  self,
@@ -1650,9 +1493,7 @@ class PreparationRepository:
1650
1493
  (run_id, version_id, stream_index),
1651
1494
  ).fetchone()
1652
1495
  if item is None:
1653
- raise ProjectError(
1654
- "preparation_item_not_found", "找不到這個分析項目。", status_code=404
1655
- )
1496
+ raise ProjectError("preparation_item_not_found", "找不到這個分析項目。", status_code=404)
1656
1497
  current_status = PreparationItemStatus(item["status"])
1657
1498
  allowed = (
1658
1499
  current_status is PreparationItemStatus.PENDING
@@ -1712,9 +1553,7 @@ class PreparationRepository:
1712
1553
  raise
1713
1554
  except sqlite3.Error as error:
1714
1555
  connection.rollback()
1715
- raise ProjectError(
1716
- "storage_failed", "Clipen 無法保存分析進度。", status_code=500
1717
- ) from error
1556
+ raise ProjectError("storage_failed", "Clipen 無法保存分析進度。", status_code=500) from error
1718
1557
 
1719
1558
  def publish(self, project_id: str, run_id: str) -> PreparationRun:
1720
1559
  validate_project_id(project_id)
@@ -1729,8 +1568,7 @@ class PreparationRepository:
1729
1568
  status_code=409,
1730
1569
  )
1731
1570
  incomplete = connection.execute(
1732
- "SELECT COUNT(*) FROM preparation_items WHERE run_id = ? "
1733
- "AND status IN ('pending', 'prepared')",
1571
+ "SELECT COUNT(*) FROM preparation_items WHERE run_id = ? AND status IN ('pending', 'prepared')",
1734
1572
  (run_id,),
1735
1573
  ).fetchone()[0]
1736
1574
  if incomplete:
@@ -1801,9 +1639,7 @@ class PreparationRepository:
1801
1639
  raise
1802
1640
  except sqlite3.Error as error:
1803
1641
  connection.rollback()
1804
- raise ProjectError(
1805
- "storage_failed", "Clipen 無法完成素材分析。", status_code=500
1806
- ) from error
1642
+ raise ProjectError("storage_failed", "Clipen 無法完成素材分析。", status_code=500) from error
1807
1643
 
1808
1644
  def interrupt_incomplete(self, project_id: str) -> int:
1809
1645
  validate_project_id(project_id)
@@ -1834,9 +1670,7 @@ class PreparationRepository:
1834
1670
  return len(rows)
1835
1671
  except sqlite3.Error as error:
1836
1672
  connection.rollback()
1837
- raise ProjectError(
1838
- "storage_failed", "Clipen 無法恢復素材分析狀態。", status_code=500
1839
- ) from error
1673
+ raise ProjectError("storage_failed", "Clipen 無法恢復素材分析狀態。", status_code=500) from error
1840
1674
 
1841
1675
  @staticmethod
1842
1676
  def _refresh_counts(connection: sqlite3.Connection, run_id: str) -> None:
@@ -1943,17 +1777,13 @@ class PreparationRepository:
1943
1777
  row["completed_at"],
1944
1778
  )
1945
1779
  except (TypeError, ValueError) as error:
1946
- raise ProjectError(
1947
- "storage_corrupt", "Clipen 無法讀取素材分析。", status_code=500
1948
- ) from error
1780
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取素材分析。", status_code=500) from error
1949
1781
 
1950
1782
  @staticmethod
1951
1783
  def _read_chunk(row: sqlite3.Row) -> PreparationChunk:
1952
1784
  try:
1953
1785
  raw_span = json.loads(row["source_span_json"])
1954
- raw_result = (
1955
- None if row["result_json"] is None else json.loads(row["result_json"])
1956
- )
1786
+ raw_result = None if row["result_json"] is None else json.loads(row["result_json"])
1957
1787
  return PreparationChunk(
1958
1788
  row["ordinal"],
1959
1789
  row["start_sample"],
@@ -1961,14 +1791,10 @@ class PreparationRepository:
1961
1791
  SourceSpan.from_storage(raw_span),
1962
1792
  PreparationChunkStatus(row["status"]),
1963
1793
  row["transcript_artifact_id"],
1964
- None
1965
- if raw_result is None
1966
- else TranscriptionResult.from_storage(raw_result),
1794
+ None if raw_result is None else TranscriptionResult.from_storage(raw_result),
1967
1795
  )
1968
1796
  except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
1969
- raise ProjectError(
1970
- "storage_corrupt", "Clipen 無法讀取逐字稿切塊。", status_code=500
1971
- ) from error
1797
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取逐字稿切塊。", status_code=500) from error
1972
1798
 
1973
1799
 
1974
1800
  def _source_span(version_id: str, stream_index: int, details: Mapping[str, Any]) -> SourceSpan:
@@ -1990,22 +1816,14 @@ def _source_span(version_id: str, stream_index: int, details: Mapping[str, Any])
1990
1816
 
1991
1817
 
1992
1818
  def _verify_inventory_root(root: InventoryRoot) -> None:
1993
- flags = (
1994
- os.O_RDONLY
1995
- | getattr(os, "O_DIRECTORY", 0)
1996
- | getattr(os, "O_NOFOLLOW", 0)
1997
- )
1819
+ flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
1998
1820
  try:
1999
1821
  descriptor = os.open(root.canonical_path, flags)
2000
1822
  except OSError as error:
2001
- raise ProjectError(
2002
- "root_unavailable", "素材磁碟目前無法使用。", status_code=409
2003
- ) from error
1823
+ raise ProjectError("root_unavailable", "素材磁碟目前無法使用。", status_code=409) from error
2004
1824
  try:
2005
1825
  if os.fstat(descriptor).st_ino != root.inode:
2006
- raise ProjectError(
2007
- "root_changed", "素材位置已改變,請重新檢查素材。", status_code=409
2008
- )
1826
+ raise ProjectError("root_changed", "素材位置已改變,請重新檢查素材。", status_code=409)
2009
1827
  finally:
2010
1828
  os.close(descriptor)
2011
1829