cjm-capability-ffmpeg 0.0.25__py3-none-any.whl

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.
@@ -0,0 +1 @@
1
+ __version__ = "0.0.25"
@@ -0,0 +1,400 @@
1
+ """FFmpeg-based media processing capability implementing the MediaProcessingCapability interface.
2
+
3
+ Stage 8 (Option C / PILLAR 1c): the tool re-bases onto ToolCapability (pure
4
+ compute). The cache/persist bookends + the (action,input,config)->output_dir
5
+ choice moved OUT to the generic media-processing adapter
6
+ (cjm-media-processing-adapter-interface); the result DTOs live in
7
+ cjm-capability-primitives. The adapter tells each artifact op WHERE to write.
8
+ The ffmpeg helpers under utils/ were lifted from the retired cjm-ffmpeg-utils
9
+ into this capability."""
10
+
11
+ import json
12
+ import logging
13
+ import os
14
+ import subprocess
15
+ import uuid
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+ from typing import Any, Dict, List, Optional, Union
19
+
20
+ from cjm_capability_ffmpeg.utils.availability import FFMPEG_AVAILABLE
21
+ from cjm_capability_ffmpeg.utils.codec import get_audio_codec
22
+ from cjm_capability_ffmpeg.utils.probe import get_media_duration
23
+ from cjm_capability_ffmpeg.utils.progress import run_ffmpeg_with_progress
24
+ from cjm_capability_ffmpeg.utils.segments import extract_audio_segment
25
+ from cjm_capability_primitives.media_processing import (MediaArtifactResult, MediaMetadata,
26
+ MediaSegment, MediaSegmentationResult)
27
+ from cjm_substrate.core.capability import ToolCapability
28
+ from cjm_substrate.core.errors import CapabilityInputError
29
+ from cjm_substrate.utils.validation import (config_to_dict, dataclass_to_jsonschema, dict_to_config,
30
+ SCHEMA_DESC, SCHEMA_ENUM, SCHEMA_TITLE)
31
+
32
+
33
+ @dataclass
34
+ class FFmpegCapabilityConfig:
35
+ """Configuration for the FFmpeg processing tool (the HOW knobs only).
36
+
37
+ Per-call WHAT-to-produce params (output_format / sample_rate / channels /
38
+ boundaries) are method arguments the adapter hashes into the cache key, NOT
39
+ config — only the quality/engine knobs live here. (The fused-era `output_dir`
40
+ config field is gone: the adapter chooses the output location, stage-8 L6.)"""
41
+
42
+ default_audio_format: str = field(
43
+ default="mp3",
44
+ metadata={
45
+ SCHEMA_TITLE: "Default Audio Format",
46
+ SCHEMA_DESC: "Fallback format for audio extraction when the source codec has no clean container mapping.",
47
+ SCHEMA_ENUM: ["mp3", "wav", "flac", "aac", "ogg", "m4a"]
48
+ }
49
+ )
50
+
51
+ default_audio_bitrate: str = field(
52
+ default="192k",
53
+ metadata={
54
+ SCHEMA_TITLE: "Default Audio Bitrate",
55
+ SCHEMA_DESC: "Bitrate for audio encoding operations (a quality knob; in the adapter cache key via get_current_config).",
56
+ SCHEMA_ENUM: ["128k", "192k", "256k", "320k"]
57
+ }
58
+ )
59
+
60
+ prefer_stream_copy: bool = field(
61
+ default=True,
62
+ metadata={
63
+ SCHEMA_TITLE: "Prefer Stream Copy",
64
+ SCHEMA_DESC: "When possible, copy the audio stream without re-encoding (faster, lossless)."
65
+ }
66
+ )
67
+
68
+ resampler: str = field(
69
+ default="soxr",
70
+ metadata={
71
+ SCHEMA_TITLE: "Resampler",
72
+ SCHEMA_DESC: "Audio resampling engine for sample-rate conversion. 'soxr' (libsoxr, high quality, matches librosa's soxr_hq) is preferred over ffmpeg's default 'swr'; needs an ffmpeg built --enable-libsoxr.",
73
+ SCHEMA_ENUM: ["soxr", "swr"]
74
+ }
75
+ )
76
+
77
+
78
+ class FFmpegProcessingCapability(ToolCapability):
79
+ """FFmpeg-based media-processing tool capability (stage 8: pure compute).
80
+
81
+ Native-surface model (PILLAR 1c): PURE COMPUTE. The artifact ops
82
+ (`convert`/`segment_audio`/`extract_audio`) read input, run ffmpeg, and WRITE
83
+ file(s) into the adapter-supplied `output_dir`, returning typed DTOs;
84
+ `get_info` probes and returns `MediaMetadata`. The cache-check +
85
+ output-location choice + persistence live in the generic media-processing
86
+ adapter (cjm-media-processing-adapter-interface); result DTOs live in
87
+ cjm-capability-primitives; identity derives from the installed distribution.
88
+ No `get_plugin_metadata`, no `self.storage`, no in-tool cache, no
89
+ `execute`/`@capability_action` dispatcher (the task channel routes by method).
90
+
91
+ Config = the HOW knobs (resampler engine, bitrate, stream-copy preference,
92
+ fallback format); the per-call output_format/sample_rate/channels/boundaries
93
+ are WHAT-to-produce request params the adapter hashes into the cache key.
94
+ The fused-era `extract_segment` action was DROPPED (no consumer; the HITL
95
+ audio-chunk read is a future in-memory op, a different shape)."""
96
+
97
+ config_class = FFmpegCapabilityConfig
98
+
99
+ def __init__(self):
100
+ """Initialize the FFmpeg processing tool."""
101
+ self.logger = logging.getLogger(f"{__name__}.{type(self).__name__}")
102
+ self.config: Optional[FFmpegCapabilityConfig] = None
103
+
104
+ @property
105
+ def name(self) -> str: # Tool identity, derived from the installed distribution (PILLAR 1c)
106
+ from importlib.metadata import metadata, packages_distributions
107
+ dist = (packages_distributions().get(__package__) or [__package__.replace("_", "-")])[0]
108
+ return metadata(dist)["Name"]
109
+
110
+ @property
111
+ def version(self) -> str: # Tool version
112
+ from cjm_capability_ffmpeg import __version__
113
+ return __version__
114
+
115
+ def initialize(self,
116
+ config: Optional[Any] = None, # Configuration dict or None for defaults
117
+ ) -> None:
118
+ """First-time setup. No storage init — the adapter owns the cache (stage 8)."""
119
+ self.config = dict_to_config(FFmpegCapabilityConfig, config or {})
120
+ self.logger.info(f"Initialized FFmpeg tool (format={self.config.default_audio_format})")
121
+
122
+ def get_config_schema(self) -> Dict[str, Any]: # JSON Schema for UI form generation
123
+ """Return the JSON Schema for tool configuration."""
124
+ return dataclass_to_jsonschema(FFmpegCapabilityConfig)
125
+
126
+ def get_current_config(self) -> Dict[str, Any]: # Current config as dict
127
+ """Return the current configuration as a dictionary."""
128
+ return config_to_dict(self.config) if self.config else {}
129
+
130
+ def is_available(self) -> bool: # Whether ffmpeg is installed
131
+ """Check if ffmpeg is available on this system."""
132
+ return FFMPEG_AVAILABLE
133
+
134
+ # ------------------------------------------------------------------
135
+ # Private helper
136
+ # ------------------------------------------------------------------
137
+
138
+ def _detect_audio_codec(self,
139
+ file_path: str, # Path to media file
140
+ ) -> Optional[str]: # Audio codec name or None
141
+ """Detect the audio codec in a media file via ffprobe."""
142
+ cmd = [
143
+ 'ffprobe', '-v', 'quiet',
144
+ '-select_streams', 'a:0',
145
+ '-show_entries', 'stream=codec_name',
146
+ '-of', 'csv=p=0',
147
+ file_path
148
+ ]
149
+ try:
150
+ result = subprocess.run(cmd, check=True, capture_output=True, text=True)
151
+ codec = result.stdout.strip()
152
+ return codec if codec else None
153
+ except subprocess.CalledProcessError:
154
+ return None
155
+
156
+ # ------------------------------------------------------------------
157
+ # Pure-compute probe (uncached)
158
+ # ------------------------------------------------------------------
159
+
160
+ def get_info(self,
161
+ file_path: Union[str, Path], # Path to media file
162
+ ) -> MediaMetadata: # Probed metadata
163
+ """Probe metadata for a media file via ffprobe (UNCACHED pure-query)."""
164
+ file_path = str(file_path)
165
+ if not os.path.exists(file_path):
166
+ raise CapabilityInputError( # SG-47: missing input file
167
+ f"File not found: {file_path}", fields_invalid=["file_path"],
168
+ )
169
+
170
+ cmd = [
171
+ 'ffprobe', '-v', 'quiet',
172
+ '-show_format', '-show_streams', '-of', 'json',
173
+ file_path
174
+ ]
175
+ result = subprocess.run(cmd, check=True, capture_output=True, text=True)
176
+ probe_data = json.loads(result.stdout)
177
+
178
+ format_info = probe_data.get('format', {})
179
+ duration = float(format_info.get('duration', 0))
180
+ size_bytes = int(format_info.get('size', 0))
181
+ container_format = format_info.get('format_name', '')
182
+
183
+ video_streams = []
184
+ audio_streams = []
185
+ for stream in probe_data.get('streams', []):
186
+ codec_type = stream.get('codec_type', '')
187
+ if codec_type == 'video':
188
+ video_streams.append({
189
+ 'codec': stream.get('codec_name'),
190
+ 'width': stream.get('width'),
191
+ 'height': stream.get('height'),
192
+ 'fps': stream.get('r_frame_rate'),
193
+ })
194
+ elif codec_type == 'audio':
195
+ stream_duration = float(stream.get('duration', duration))
196
+ audio_streams.append({
197
+ 'codec': stream.get('codec_name'),
198
+ 'sample_rate': int(stream.get('sample_rate', 0)),
199
+ 'channels': int(stream.get('channels', 0)),
200
+ 'duration': stream_duration,
201
+ })
202
+
203
+ return MediaMetadata(
204
+ path=file_path,
205
+ duration=duration,
206
+ format=container_format,
207
+ size_bytes=size_bytes,
208
+ video_streams=video_streams,
209
+ audio_streams=audio_streams,
210
+ )
211
+
212
+ # ------------------------------------------------------------------
213
+ # Pure-compute artifact ops (write into the adapter-supplied output_dir)
214
+ # ------------------------------------------------------------------
215
+
216
+ def convert(self,
217
+ input_path: Union[str, Path], # Source (or upstream artifact) media to convert
218
+ output_dir: str, # Adapter-chosen dir to write the artifact into
219
+ output_format: str, # Target audio format (e.g. 'wav', 'mp3')
220
+ sample_rate: Optional[int] = None, # Target sample rate (e.g. 16000); None = source rate
221
+ channels: Optional[int] = None, # Target channel count (e.g. 1 = mono); None = source
222
+ **kwargs # Provenance pass-through (unused by compute)
223
+ ) -> MediaArtifactResult: # The produced converted-audio artifact
224
+ """Convert media to target/model-ready audio — PURE COMPUTE.
225
+
226
+ Writes `<output_dir>/<stem>.<output_format>` and returns its pointer. The
227
+ quality knobs (bitrate, resampler) come from `self.config`; the shape
228
+ params (format/rate/channels) are the per-call request (the adapter hashes
229
+ them into the cache key)."""
230
+ input_path = str(input_path)
231
+ if not os.path.exists(input_path):
232
+ raise CapabilityInputError( # SG-47: missing input file
233
+ f"File not found: {input_path}", fields_invalid=["input_path"],
234
+ )
235
+
236
+ bitrate = self.config.default_audio_bitrate
237
+ resampler = self.config.resampler
238
+
239
+ os.makedirs(output_dir, exist_ok=True)
240
+ stem = Path(input_path).stem
241
+ output_path = os.path.join(output_dir, f"{stem}.{output_format}")
242
+
243
+ total_duration = get_media_duration(Path(input_path))
244
+ codec = get_audio_codec(output_format)
245
+
246
+ cmd = ['ffmpeg', '-i', input_path, '-vn', '-acodec', codec]
247
+ if bitrate:
248
+ cmd.extend(['-b:a', bitrate])
249
+ if sample_rate:
250
+ # Resample with the configured engine (soxr by default — libsoxr at HQ
251
+ # precision, matching librosa's soxr_hq), standardizing model-ready input.
252
+ if resampler:
253
+ cmd.extend(['-af', f'aresample=resampler={resampler}:precision=20'])
254
+ cmd.extend(['-ar', str(sample_rate)])
255
+ if channels:
256
+ cmd.extend(['-ac', str(channels)])
257
+ cmd.extend(['-progress', 'pipe:2', '-y', output_path])
258
+
259
+ self.report_progress(0.0, f"Converting to {output_format}...")
260
+ run_ffmpeg_with_progress(
261
+ cmd=cmd, total_duration=total_duration,
262
+ description=f"Converting to {output_format}"
263
+ )
264
+ self.report_progress(1.0, "Complete")
265
+ self.logger.info(f"Converted {input_path} -> {output_path}")
266
+
267
+ return MediaArtifactResult(output_path=output_path, metadata={
268
+ "output_format": output_format, "sample_rate": sample_rate, "channels": channels,
269
+ "resampler": resampler, "bitrate": bitrate, "duration": total_duration,
270
+ })
271
+
272
+ def segment_audio(self,
273
+ input_path: Union[str, Path], # Source audio to cut
274
+ output_dir: str, # Adapter-chosen dir to write the segments into
275
+ boundaries: List[Dict[str, float]], # [{"start", "end"}, ...]
276
+ output_format: Optional[str] = None, # Output format (default: same as input)
277
+ filename_template: str = "segment_{index:03d}", # Per-segment filename pattern
278
+ **kwargs # Provenance pass-through (unused by compute)
279
+ ) -> MediaSegmentationResult: # The produced batch of segment files
280
+ """Split an audio file into segments at the given boundaries — PURE COMPUTE.
281
+
282
+ Writes one file per boundary into `output_dir` and returns the typed batch
283
+ result. Batch-level caching is the adapter's concern (one row per
284
+ (input, boundaries+format config); the per-segment resume-skip the fused
285
+ tool did is intentionally not reproduced)."""
286
+ input_path = str(input_path)
287
+ if not os.path.exists(input_path):
288
+ raise CapabilityInputError( # SG-47: missing input file
289
+ f"File not found: {input_path}", fields_invalid=["input_path"],
290
+ )
291
+ if not boundaries:
292
+ raise CapabilityInputError( # SG-47: typed input-validation
293
+ "boundaries list must not be empty", fields_invalid=["boundaries"],
294
+ )
295
+ # Validate boundaries are sorted and non-overlapping.
296
+ for i, b in enumerate(boundaries):
297
+ if b["end"] <= b["start"]:
298
+ raise CapabilityInputError(
299
+ f"Boundary {i}: end ({b['end']}) must be > start ({b['start']})",
300
+ fields_invalid=["boundaries"],
301
+ )
302
+ if i > 0 and b["start"] < boundaries[i - 1]["end"]:
303
+ raise CapabilityInputError(
304
+ f"Boundary {i} start ({b['start']}) overlaps boundary {i-1} end ({boundaries[i-1]['end']})",
305
+ fields_invalid=["boundaries"],
306
+ )
307
+
308
+ ext = output_format or Path(input_path).suffix.lstrip('.')
309
+ os.makedirs(output_dir, exist_ok=True)
310
+ batch_key = str(uuid.uuid4())
311
+ total = len(boundaries)
312
+
313
+ segments: List[MediaSegment] = []
314
+ for i, boundary in enumerate(boundaries):
315
+ start = boundary["start"]
316
+ end = boundary["end"]
317
+ duration = end - start
318
+ filename = f"{filename_template.format(index=i)}.{ext}"
319
+ output_path = os.path.join(output_dir, filename)
320
+ extract_audio_segment(
321
+ input_path=Path(input_path),
322
+ output_path=Path(output_path),
323
+ start_time=str(start),
324
+ duration=str(duration),
325
+ )
326
+ segments.append(MediaSegment(
327
+ index=i, output_path=output_path, start=start, end=end, duration=duration,
328
+ ))
329
+ self.report_progress((i + 1) / total, f"Segment {i + 1}/{total}")
330
+
331
+ total_duration = sum(s.duration for s in segments)
332
+ self.report_progress(1.0, f"Complete: {total} segments")
333
+ self.logger.info(f"Segmented {input_path} into {total} segments (batch_key={batch_key})")
334
+
335
+ return MediaSegmentationResult(
336
+ segments=segments, input_path=input_path, segment_count=total,
337
+ total_duration=total_duration, batch_key=batch_key,
338
+ )
339
+
340
+ def extract_audio(self,
341
+ input_path: Union[str, Path], # Source video container
342
+ output_dir: str, # Adapter-chosen dir to write the artifact into
343
+ output_format: Optional[str] = None, # Audio format (default: from codec detection)
344
+ **kwargs # Provenance pass-through (unused by compute)
345
+ ) -> MediaArtifactResult: # The produced extracted-audio artifact
346
+ """Extract the audio stream from a video container — PURE COMPUTE.
347
+
348
+ Stream-copies when the source codec maps cleanly (lossless, fast),
349
+ otherwise re-encodes to the resolved format. Writes into `output_dir`."""
350
+ input_path = str(input_path)
351
+ if not os.path.exists(input_path):
352
+ raise CapabilityInputError( # SG-47: missing input file
353
+ f"File not found: {input_path}", fields_invalid=["input_path"],
354
+ )
355
+
356
+ codec = self._detect_audio_codec(input_path)
357
+ if not codec:
358
+ raise CapabilityInputError( # SG-47: input file has no audio stream
359
+ f"No audio stream found in: {input_path}", fields_invalid=["input_path"],
360
+ )
361
+
362
+ stream_copy = self.config.prefer_stream_copy
363
+ if output_format is None:
364
+ codec_ext_map = {
365
+ 'aac': 'm4a', 'mp3': 'mp3', 'vorbis': 'ogg', 'opus': 'ogg',
366
+ 'flac': 'flac', 'pcm_s16le': 'wav', 'pcm_s24le': 'wav',
367
+ }
368
+ output_format = codec_ext_map.get(codec, self.config.default_audio_format)
369
+ if codec not in codec_ext_map:
370
+ stream_copy = False
371
+ else:
372
+ expected_codec = get_audio_codec(output_format)
373
+ if expected_codec != 'copy' and expected_codec != codec:
374
+ stream_copy = False
375
+
376
+ os.makedirs(output_dir, exist_ok=True)
377
+ stem = Path(input_path).stem
378
+ output_path = os.path.join(output_dir, f"{stem}.{output_format}")
379
+ total_duration = get_media_duration(Path(input_path))
380
+
381
+ cmd = ['ffmpeg', '-i', input_path, '-vn']
382
+ if stream_copy:
383
+ cmd.extend(['-acodec', 'copy'])
384
+ else:
385
+ cmd.extend(['-acodec', get_audio_codec(output_format)])
386
+ cmd.extend(['-b:a', self.config.default_audio_bitrate])
387
+ cmd.extend(['-progress', 'pipe:2', '-y', output_path])
388
+
389
+ self.report_progress(0.1, "Extracting audio stream...")
390
+ run_ffmpeg_with_progress(
391
+ cmd=cmd, total_duration=total_duration,
392
+ description="Extracting audio"
393
+ )
394
+ self.report_progress(1.0, "Complete")
395
+ self.logger.info(f"Extracted audio {input_path} -> {output_path} (stream_copy={stream_copy})")
396
+
397
+ return MediaArtifactResult(output_path=output_path, metadata={
398
+ "codec": codec, "duration": total_duration, "output_format": output_format,
399
+ "stream_copy": stream_copy, "source_video_path": input_path,
400
+ })
File without changes
@@ -0,0 +1,12 @@
1
+ """Detect whether the ffmpeg binary is installed on this system."""
2
+
3
+ import logging
4
+ import shutil
5
+
6
+ # Verify FFmpeg installation. True when the `ffmpeg` binary is on PATH.
7
+ FFMPEG_AVAILABLE = shutil.which("ffmpeg") is not None
8
+ if not FFMPEG_AVAILABLE:
9
+ logging.warning(
10
+ "FFmpeg not available - install the system package "
11
+ "(e.g. apt install ffmpeg, brew install ffmpeg, or https://ffmpeg.org/)"
12
+ )
@@ -0,0 +1,15 @@
1
+ """Map audio container formats to the ffmpeg codec used to encode them."""
2
+
3
+
4
+ def get_audio_codec(audio_format: str # The desired audio format (e.g. 'mp3', 'wav')
5
+ ) -> str: # The ffmpeg audio codec name ('copy' if unknown)
6
+ """Map an audio container format to the appropriate ffmpeg codec."""
7
+ codec_map = {
8
+ 'mp3': 'libmp3lame',
9
+ 'wav': 'pcm_s16le',
10
+ 'flac': 'flac',
11
+ 'aac': 'aac',
12
+ 'ogg': 'libvorbis',
13
+ 'm4a': 'aac',
14
+ }
15
+ return codec_map.get(audio_format.lower(), 'copy')
@@ -0,0 +1,24 @@
1
+ """Probe media files for metadata (duration, ...) via ffprobe."""
2
+
3
+ import subprocess
4
+ from pathlib import Path
5
+ from typing import Optional
6
+
7
+
8
+ def get_media_duration(file_path: Path # Path to the media file
9
+ ) -> Optional[float]: # Duration in seconds, or None if it cannot be determined
10
+ """Get the duration of a media file (seconds) via ffprobe."""
11
+ duration_cmd = [
12
+ 'ffprobe',
13
+ '-v', 'quiet',
14
+ '-show_entries', 'format=duration',
15
+ '-of', 'csv=p=0',
16
+ str(file_path),
17
+ ]
18
+ try:
19
+ duration_result = subprocess.run(
20
+ duration_cmd, check=True, capture_output=True, text=True,
21
+ )
22
+ return float(duration_result.stdout.strip())
23
+ except (subprocess.CalledProcessError, ValueError, FileNotFoundError):
24
+ return None
@@ -0,0 +1,97 @@
1
+ """Run ffmpeg subprocess commands with a progress bar and optional callback."""
2
+
3
+ import subprocess
4
+ from typing import Callable, List, Optional
5
+
6
+ from tqdm.auto import tqdm
7
+
8
+
9
+ def parse_progress_line(line: str # A line of stderr output from ffmpeg
10
+ ) -> Optional[float]: # Current time in seconds, or None if the line has no progress info
11
+ """Parse a progress line from ffmpeg stderr output."""
12
+ # Look for time progress in the format "out_time_ms=123456789"
13
+ if line.startswith('out_time_ms='):
14
+ try:
15
+ time_ms = int(line.strip().split('=')[1])
16
+ return time_ms / 1000000.0 # microseconds -> seconds
17
+ except (ValueError, IndexError):
18
+ pass
19
+ # Alternative: look for time in the format "time=00:01:23.45"
20
+ elif line.startswith('time='):
21
+ try:
22
+ time_str = line.strip().split('=')[1]
23
+ time_parts = time_str.split(':')
24
+ if len(time_parts) == 3:
25
+ hours = float(time_parts[0])
26
+ minutes = float(time_parts[1])
27
+ seconds = float(time_parts[2])
28
+ return hours * 3600 + minutes * 60 + seconds
29
+ except (ValueError, IndexError):
30
+ pass
31
+ return None
32
+
33
+
34
+ def run_ffmpeg_with_progress(
35
+ cmd: List[str], # The ffmpeg command and arguments
36
+ total_duration: Optional[float] = None, # Total duration in seconds for a determinate bar, else indeterminate
37
+ description: str = "Processing", # Description text for the progress bar
38
+ verbose: bool = False, # If True, prints detailed ffmpeg output
39
+ progress_callback: Optional[Callable[[float], None]] = None # Optional callback receiving current progress in seconds
40
+ ) -> None: # Raises FileNotFoundError or subprocess.CalledProcessError on failure
41
+ """Run an ffmpeg command with a progress bar."""
42
+ try:
43
+ if total_duration:
44
+ pbar = tqdm(
45
+ total=total_duration, unit='s', desc=description,
46
+ bar_format='{l_bar}{bar}| {n:.1f}/{total:.1f}s [{elapsed}<{remaining}]',
47
+ )
48
+ else:
49
+ pbar = tqdm(desc=description, unit='frames')
50
+
51
+ process = subprocess.Popen(
52
+ cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
53
+ text=True, bufsize=1, universal_newlines=True,
54
+ )
55
+
56
+ while process.poll() is None: # while the process is running
57
+ line = process.stderr.readline()
58
+ if not line:
59
+ continue
60
+ if verbose:
61
+ print(line.strip())
62
+ current_time = parse_progress_line(line)
63
+ if current_time is not None:
64
+ if total_duration:
65
+ pbar.n = min(current_time, total_duration)
66
+ pbar.refresh()
67
+ else:
68
+ pbar.update(1)
69
+ if progress_callback:
70
+ progress_callback(current_time)
71
+
72
+ remaining_stderr = process.stderr.read()
73
+ if verbose and remaining_stderr:
74
+ print(remaining_stderr)
75
+
76
+ return_code = process.returncode
77
+ if total_duration:
78
+ pbar.n = total_duration
79
+ pbar.refresh()
80
+ pbar.close()
81
+
82
+ if return_code != 0:
83
+ stderr_output = remaining_stderr or ""
84
+ error_msg = f"FFmpeg failed with return code {return_code}"
85
+ if stderr_output:
86
+ error_msg += f"\nError output: {stderr_output}"
87
+ raise subprocess.CalledProcessError(return_code, cmd, error_msg)
88
+ except FileNotFoundError:
89
+ if 'pbar' in locals():
90
+ pbar.close()
91
+ raise FileNotFoundError(
92
+ "ffmpeg not found. Please install ffmpeg and ensure it's in your PATH."
93
+ )
94
+ except Exception:
95
+ if 'pbar' in locals():
96
+ pbar.close()
97
+ raise
@@ -0,0 +1,52 @@
1
+ """Extract temporal segments from audio files via ffmpeg stream-copy."""
2
+
3
+ import subprocess
4
+ from pathlib import Path
5
+
6
+ from cjm_capability_ffmpeg.utils.progress import run_ffmpeg_with_progress
7
+
8
+
9
+ def extract_audio_segment(input_path: Path, # Path to the input audio file
10
+ output_path: Path, # Path where the extracted segment is saved
11
+ start_time: str, # Start time as "HH:MM:SS" or seconds
12
+ duration: str, # Duration as "HH:MM:SS" or seconds
13
+ verbose: bool = False, # If True, shows verbose ffmpeg output
14
+ pbar: bool = False, # If True, shows a progress bar
15
+ copy_codec: bool = True, # Stream-copy without re-encoding (fast)
16
+ ) -> None: # Raises subprocess.CalledProcessError if extraction fails
17
+ """Extract a temporal segment from an audio file."""
18
+ # Compute the expected segment duration for the progress bar.
19
+ try:
20
+ segment_duration = float(duration)
21
+ except ValueError:
22
+ time_parts = duration.split(':')
23
+ if len(time_parts) == 3:
24
+ hours = float(time_parts[0])
25
+ minutes = float(time_parts[1])
26
+ seconds = float(time_parts[2])
27
+ segment_duration = hours * 3600 + minutes * 60 + seconds
28
+ else:
29
+ segment_duration = None
30
+
31
+ # Place -ss before -i for fast input seeking (seeks to the nearest keyframe).
32
+ cmd = [
33
+ 'ffmpeg',
34
+ '-ss', start_time,
35
+ '-i', str(input_path),
36
+ '-t', duration,
37
+ ]
38
+ if copy_codec:
39
+ cmd.extend(['-acodec', 'copy'])
40
+ cmd.extend(['-progress', 'pipe:2', '-y', str(output_path)])
41
+
42
+ if pbar:
43
+ run_ffmpeg_with_progress(
44
+ cmd=cmd, total_duration=segment_duration,
45
+ description="Extracting segment", verbose=verbose,
46
+ )
47
+ else:
48
+ result = subprocess.run(
49
+ cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True,
50
+ )
51
+ if result.returncode != 0:
52
+ raise subprocess.CalledProcessError(result.returncode, cmd)
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.4
2
+ Name: cjm-capability-ffmpeg
3
+ Version: 0.0.25
4
+ Summary: An FFmpeg-based media-processing capability for the cjm-substrate runtime that provides audio extraction, segmentation, and format conversion.
5
+ Author-email: "Christian J. Mills" <9126128+cj-mills@users.noreply.github.com>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/cj-mills/cjm-capability-ffmpeg
8
+ Keywords: python
9
+ Classifier: Natural Language :: English
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Requires-Python: >=3.12
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: cjm-substrate>=0.0.51
18
+ Requires-Dist: cjm-capability-primitives>=0.0.10
19
+ Requires-Dist: tqdm
20
+ Dynamic: license-file
21
+
22
+ # cjm-capability-ffmpeg
23
+
24
+ <!-- generated from the context graph by `cjm-context-graph readme` — do not edit by hand; edit the graph (the urge to hand-edit = move it on-graph) -->
25
+
26
+ An FFmpeg-based media-processing capability for the cjm-substrate runtime that provides audio extraction, segmentation, and format conversion.
27
+
28
+ ## Modules
29
+
30
+ - **`cjm_capability_ffmpeg.capability`** — FFmpeg-based media processing capability implementing the MediaProcessingCapability interface.
31
+ - **`cjm_capability_ffmpeg.utils.availability`** — Detect whether the ffmpeg binary is installed on this system.
32
+ - **`cjm_capability_ffmpeg.utils.codec`** — Map audio container formats to the ffmpeg codec used to encode them.
33
+ - **`cjm_capability_ffmpeg.utils.probe`** — Probe media files for metadata (duration, ...) via ffprobe.
34
+ - **`cjm_capability_ffmpeg.utils.progress`** — Run ffmpeg subprocess commands with a progress bar and optional callback.
35
+ - **`cjm_capability_ffmpeg.utils.segments`** — Extract temporal segments from audio files via ffmpeg stream-copy.
36
+
37
+ ## API
38
+
39
+ ### `cjm_capability_ffmpeg.capability`
40
+
41
+ - `FFmpegCapabilityConfig` _class_ — Configuration for the FFmpeg processing tool (the HOW knobs only).
42
+ - `FFmpegProcessingCapability` _class_ — FFmpeg-based media-processing tool capability (stage 8: pure compute).
43
+
44
+ ### `cjm_capability_ffmpeg.utils.codec`
45
+
46
+ - `get_audio_codec` _function_ — Map an audio container format to the appropriate ffmpeg codec.
47
+
48
+ ### `cjm_capability_ffmpeg.utils.probe`
49
+
50
+ - `get_media_duration` _function_ — Get the duration of a media file (seconds) via ffprobe.
51
+
52
+ ### `cjm_capability_ffmpeg.utils.progress`
53
+
54
+ - `parse_progress_line` _function_ — Parse a progress line from ffmpeg stderr output.
55
+ - `run_ffmpeg_with_progress` _function_ — Run an ffmpeg command with a progress bar.
56
+
57
+ ### `cjm_capability_ffmpeg.utils.segments`
58
+
59
+ - `extract_audio_segment` _function_ — Extract a temporal segment from an audio file.
@@ -0,0 +1,13 @@
1
+ cjm_capability_ffmpeg/__init__.py,sha256=ognSasPrsQjE8uJUk5Fcsl4caTERui00vZnmFlQnMoU,23
2
+ cjm_capability_ffmpeg/capability.py,sha256=JMOgFQIKTANvNzMe8qONcSN5xuDx8IMfqUafJqjQuso,19062
3
+ cjm_capability_ffmpeg/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ cjm_capability_ffmpeg/utils/availability.py,sha256=t3yfTOkYiAwcHzRW1UbOB7oz3vheAWzHewyQtG0zz8c,419
5
+ cjm_capability_ffmpeg/utils/codec.py,sha256=X-B2jw3BbXLUKj1FGV4eUp6c6adyXH6FuXujyF8Plko,548
6
+ cjm_capability_ffmpeg/utils/probe.py,sha256=hNDVXNHQVz2uujVe7OeNj8PtMMtOSqPZ7kJdao8-I80,816
7
+ cjm_capability_ffmpeg/utils/progress.py,sha256=AwmgdNt5kL3wZzpNAH7dEfulHLYclS0kLjcxlJO08KU,3828
8
+ cjm_capability_ffmpeg/utils/segments.py,sha256=Ruz0fsGfX4uyd9x83KFBTRURWzoEy6m2oj5szzATh4I,2132
9
+ cjm_capability_ffmpeg-0.0.25.dist-info/licenses/LICENSE,sha256=xV8xoN4VOL0uw9X8RSs2IMuD_Ss_a9yAbtGNeBWZwnw,11337
10
+ cjm_capability_ffmpeg-0.0.25.dist-info/METADATA,sha256=06TfKe6GcdyMX7w4aBt6Zawo3nT67DRIWDfuC5fOHpE,2806
11
+ cjm_capability_ffmpeg-0.0.25.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
12
+ cjm_capability_ffmpeg-0.0.25.dist-info/top_level.txt,sha256=S6sh1sdHi7wMuCAncf9Z-fPbxJJQzCE7SBfmUnwAApo,22
13
+ cjm_capability_ffmpeg-0.0.25.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2022, fastai
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ cjm_capability_ffmpeg