syncnet-python 0.2.1__py3-none-any.whl → 0.2.3__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.
@@ -4,23 +4,34 @@ This package provides a PyTorch implementation of SyncNet for detecting
4
4
  synchronization between audio and video in multimedia content.
5
5
  """
6
6
 
7
- __version__ = "0.1.1"
7
+ __version__ = "0.2.3"
8
8
 
9
- # Import main components
9
+ # Import main components. An ImportError here (for example a missing
10
+ # dependency or an incompatible scenedetect version) is raised with its
11
+ # original message instead of being replaced by None.
10
12
  try:
11
13
  from .syncnet_pipeline import SyncNetPipeline
12
14
  from .SyncNetModel import S as SyncNetModel
13
15
  from .SyncNetInstance import SyncNetInstance
14
- except ImportError:
15
- # Fallback for development
16
- SyncNetPipeline = None
17
- SyncNetModel = None
18
- SyncNetInstance = None
16
+ from .safe_syncnet_utils import (
17
+ safe_syncnet_inference,
18
+ extract_audio_from_video,
19
+ calculate_lse_metrics
20
+ )
21
+ except ImportError as e:
22
+ raise ImportError(
23
+ f"syncnet_python could not import its components: {e}. "
24
+ "Check that the dependencies are installed with the versions listed "
25
+ "in pyproject.toml (scenedetect must be >=0.6,<0.7)."
26
+ ) from e
19
27
 
20
28
  __all__ = [
21
29
  "SyncNetPipeline",
22
30
  "SyncNetModel",
23
31
  "SyncNetInstance",
32
+ "safe_syncnet_inference",
33
+ "extract_audio_from_video",
34
+ "calculate_lse_metrics",
24
35
  "__version__"
25
36
  ]
26
37
 
@@ -0,0 +1,154 @@
1
+ """Safe SyncNet utilities with comprehensive error handling."""
2
+
3
+ import logging
4
+ import tempfile
5
+ import os
6
+ from pathlib import Path
7
+ from typing import Optional, Tuple, List
8
+ try:
9
+ from .syncnet_pipeline import SyncNetPipeline
10
+ except ImportError:
11
+ from syncnet_pipeline import SyncNetPipeline
12
+
13
+
14
+ def safe_syncnet_inference(
15
+ pipeline: SyncNetPipeline,
16
+ video_path: str,
17
+ audio_path: Optional[str] = None,
18
+ cache_dir: Optional[str] = None
19
+ ) -> Tuple[List[int], List[float], List[float], float, float, str, bool]:
20
+ """
21
+ Safe SyncNet inference with automatic audio extraction if needed.
22
+
23
+ This function provides a wrapper around SyncNetPipeline.inference() that:
24
+ 1. Handles audio_path=None by automatically extracting audio from video
25
+ 2. Provides comprehensive error handling and logging
26
+ 3. Ensures proper cleanup of temporary files
27
+
28
+ Args:
29
+ pipeline: Initialized SyncNetPipeline instance
30
+ video_path: Path to input video file
31
+ audio_path: Path to audio file (None for auto-extraction from video)
32
+ cache_dir: Directory for temporary files (None for auto-cleanup)
33
+
34
+ Returns:
35
+ Tuple of (offsets, confidences, distances, max_conf, min_dist, s3fd_json, has_face)
36
+
37
+ Raises:
38
+ RuntimeError: If processing fails at any stage
39
+ FileNotFoundError: If video file doesn't exist
40
+ ValueError: If video format is not supported
41
+ """
42
+ if not os.path.exists(video_path):
43
+ raise FileNotFoundError(f"Video file not found: {video_path}")
44
+
45
+ if audio_path and not os.path.exists(audio_path):
46
+ raise FileNotFoundError(f"Audio file not found: {audio_path}")
47
+
48
+ logging.info(f"Starting safe SyncNet inference for video: {video_path}")
49
+
50
+ try:
51
+ # Use the updated inference method that handles audio_path=None
52
+ results = pipeline.inference(
53
+ video_path=video_path,
54
+ audio_path=audio_path,
55
+ cache_dir=cache_dir
56
+ )
57
+
58
+ offsets, confs, dists, max_conf, min_dist, s3fd_json, has_face = results
59
+
60
+ # Validate results
61
+ if not has_face:
62
+ logging.warning("No faces detected in the video")
63
+ elif not offsets:
64
+ logging.warning("No valid face tracks found")
65
+ else:
66
+ logging.info(f"Successfully processed {len(offsets)} face tracks")
67
+ logging.info(f"LSE-C (max confidence): {max_conf:.3f}")
68
+ logging.info(f"LSE-D (min distance): {min_dist:.3f}")
69
+
70
+ return results
71
+
72
+ except Exception as e:
73
+ logging.error(f"SyncNet inference failed: {str(e)}")
74
+ raise RuntimeError(f"SyncNet processing failed: {str(e)}") from e
75
+
76
+
77
+ def extract_audio_from_video(video_path: str, audio_path: str) -> None:
78
+ """
79
+ Extract audio from video file using ffmpeg.
80
+
81
+ Args:
82
+ video_path: Path to input video file
83
+ audio_path: Path for output audio file
84
+
85
+ Raises:
86
+ RuntimeError: If audio extraction fails
87
+ FileNotFoundError: If video file doesn't exist
88
+ """
89
+ if not os.path.exists(video_path):
90
+ raise FileNotFoundError(f"Video file not found: {video_path}")
91
+
92
+ # Create a temporary pipeline instance just for audio extraction
93
+ pipeline = SyncNetPipeline()
94
+
95
+ try:
96
+ pipeline._extract_audio_from_video(video_path, audio_path)
97
+ logging.info(f"Successfully extracted audio from {video_path} to {audio_path}")
98
+ except Exception as e:
99
+ logging.error(f"Audio extraction failed: {str(e)}")
100
+ raise RuntimeError(f"Audio extraction failed: {str(e)}") from e
101
+
102
+
103
+ def calculate_lse_metrics(
104
+ pipeline: SyncNetPipeline,
105
+ video_path: str,
106
+ audio_path: Optional[str] = None,
107
+ cache_dir: Optional[str] = None
108
+ ) -> Tuple[float, float, str]:
109
+ """
110
+ Calculate LSE-C and LSE-D metrics for a video.
111
+
112
+ Args:
113
+ pipeline: Initialized SyncNetPipeline instance
114
+ video_path: Path to input video file
115
+ audio_path: Path to audio file (None for auto-extraction)
116
+ cache_dir: Directory for temporary files
117
+
118
+ Returns:
119
+ Tuple of (lse_c, lse_d, quality_assessment)
120
+
121
+ Raises:
122
+ RuntimeError: If metric calculation fails
123
+ """
124
+ try:
125
+ results = safe_syncnet_inference(pipeline, video_path, audio_path, cache_dir)
126
+ offsets, confs, dists, max_conf, min_dist, s3fd_json, has_face = results
127
+
128
+ if not has_face:
129
+ return 0.0, float('inf'), "NO_FACE"
130
+
131
+ if not confs or not dists:
132
+ return 0.0, float('inf'), "NO_TRACKS"
133
+
134
+ # LSE-C is the maximum confidence across all tracks
135
+ lse_c = max_conf
136
+
137
+ # LSE-D is the minimum distance across all tracks
138
+ lse_d = min_dist
139
+
140
+ # Quality assessment based on typical thresholds
141
+ if lse_c > 3.5 and lse_d < 7.0:
142
+ quality = "GOOD"
143
+ elif lse_c > 2.0 and lse_d < 10.0:
144
+ quality = "FAIR"
145
+ else:
146
+ quality = "POOR"
147
+
148
+ logging.info(f"LSE Metrics - C: {lse_c:.3f}, D: {lse_d:.3f}, Quality: {quality}")
149
+
150
+ return lse_c, lse_d, quality
151
+
152
+ except Exception as e:
153
+ logging.error(f"LSE metric calculation failed: {str(e)}")
154
+ raise RuntimeError(f"LSE metric calculation failed: {str(e)}") from e
@@ -1,3 +1,14 @@
1
+ # Modified from MoChaBench eval-lipsync/script/syncnet_pipeline.py
2
+ # (https://github.com/congwei1230/MoChaBench, Apache-2.0) by nawta:
3
+ # package-relative imports with a fallback for direct script execution;
4
+ # ffmpeg_bin defaults to "ffmpeg" when None; the two shell
5
+ # subprocess.call ffmpeg commands in _crop became subprocess.run argument
6
+ # lists that raise RuntimeError on failure; added _extract_audio_from_video
7
+ # so inference() accepts audio_path=None; the first three ffmpeg-python
8
+ # calls in inference() raise RuntimeError on ffmpeg.Error; inference()
9
+ # raises RuntimeError when no frames are extracted.
10
+ # See NOTICE for licensing.
11
+
1
12
  import json
2
13
  import logging
3
14
  import os
@@ -215,11 +226,34 @@ class SyncNetPipeline:
215
226
  os.remove(tmp_avi)
216
227
  return final_avi
217
228
 
229
+ # ---------------------------- audio extraction helper ----------------- #
230
+ def _extract_audio_from_video(self, video_path: str, output_path: str) -> None:
231
+ """Extract audio from video file using ffmpeg."""
232
+ cfg = self.cfg
233
+ ffmpeg_bin = cfg.ffmpeg_bin if cfg.ffmpeg_bin is not None else "ffmpeg"
234
+
235
+ cmd = [
236
+ ffmpeg_bin, "-y", "-i", str(video_path),
237
+ "-ac", "1", "-ar", str(cfg.audio_sample_rate),
238
+ "-acodec", "pcm_s16le", "-f", "wav",
239
+ str(output_path)
240
+ ]
241
+
242
+ try:
243
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
244
+ logging.info(f"Successfully extracted audio from {video_path} to {output_path}")
245
+ except subprocess.CalledProcessError as e:
246
+ logging.error(f"FFmpeg audio extraction failed: {e.stderr}")
247
+ raise RuntimeError(f"FFmpeg audio extraction failed: {e.stderr}")
248
+ except FileNotFoundError:
249
+ logging.error(f"FFmpeg not found at: {ffmpeg_bin}")
250
+ raise RuntimeError(f"FFmpeg not found. Please ensure ffmpeg is installed and in PATH.")
251
+
218
252
  # ---------------------------- inference -------------------------------- #
219
253
  def inference(
220
254
  self,
221
- video_path: str, # We do not extract audio from video_path!
222
- audio_path: str,
255
+ video_path: str,
256
+ audio_path: Optional[str] = None, # Now supports None for auto-extraction
223
257
  *,
224
258
  cache_dir: Optional[str] = None,
225
259
  ) -> Tuple[List[int], List[float], List[float], float, float, str, bool]:
@@ -229,34 +263,59 @@ class SyncNetPipeline:
229
263
  work.mkdir(parents=True, exist_ok=True)
230
264
 
231
265
  try:
266
+ # Handle audio_path=None case - extract audio from video
267
+ if audio_path is None:
268
+ logging.info("audio_path is None, extracting audio from video")
269
+ extracted_audio_path = work / "extracted_audio.wav"
270
+ self._extract_audio_from_video(video_path, str(extracted_audio_path))
271
+ actual_audio_path = str(extracted_audio_path)
272
+ else:
273
+ actual_audio_path = audio_path
274
+ logging.info(f"Using provided audio path: {actual_audio_path}")
275
+
232
276
  # 1) Convert video to constant-fps AVI
233
277
  avi = work / "video.avi"
234
- (
235
- ffmpeg.input(video_path)
236
- .output(str(avi), **{"q:v": 2}, r=cfg.frame_rate, **{"async": 1})
237
- .overwrite_output()
238
- .run()
239
- )
278
+ try:
279
+ (
280
+ ffmpeg.input(video_path)
281
+ .output(str(avi), **{"q:v": 2}, r=cfg.frame_rate, **{"async": 1})
282
+ .overwrite_output()
283
+ .run()
284
+ )
285
+ except ffmpeg.Error as e:
286
+ logging.error(f"FFmpeg video conversion failed: {e}")
287
+ raise RuntimeError(f"FFmpeg video conversion failed: {e}")
240
288
 
241
289
  # 2) Extract frames
242
290
  frames_dir = work / "frames"
243
291
  frames_dir.mkdir(exist_ok=True)
244
- (
245
- ffmpeg.input(str(avi))
246
- .output(str(frames_dir / "%06d.jpg"), **{"q:v": 2}, f="image2", threads=1)
247
- .overwrite_output()
248
- .run()
249
- )
292
+ try:
293
+ (
294
+ ffmpeg.input(str(avi))
295
+ .output(str(frames_dir / "%06d.jpg"), **{"q:v": 2}, f="image2", threads=1)
296
+ .overwrite_output()
297
+ .run()
298
+ )
299
+ except ffmpeg.Error as e:
300
+ logging.error(f"FFmpeg frame extraction failed: {e}")
301
+ raise RuntimeError(f"FFmpeg frame extraction failed: {e}")
302
+
250
303
  frames = sorted(glob(str(frames_dir / "*.jpg")))
304
+ if not frames:
305
+ raise RuntimeError("No frames were extracted from the video")
251
306
 
252
307
  # 3) Resample speech
253
308
  audio_wav = work / "speech.wav"
254
- (
255
- ffmpeg.input(audio_path)
256
- .output(str(audio_wav), ac=1, ar=cfg.audio_sample_rate, format="wav")
257
- .overwrite_output()
258
- .run()
259
- )
309
+ try:
310
+ (
311
+ ffmpeg.input(actual_audio_path)
312
+ .output(str(audio_wav), ac=1, ar=cfg.audio_sample_rate, format="wav")
313
+ .overwrite_output()
314
+ .run()
315
+ )
316
+ except ffmpeg.Error as e:
317
+ logging.error(f"FFmpeg audio resampling failed: {e}")
318
+ raise RuntimeError(f"FFmpeg audio resampling failed: {e}")
260
319
 
261
320
  # 4) Face detection
262
321
  detections = []
@@ -0,0 +1,141 @@
1
+ #!/usr/bin/env python3
2
+ """Test script for comprehensive error handling in SyncNet v0.2.2."""
3
+
4
+ import logging
5
+ import tempfile
6
+ from pathlib import Path
7
+ import sys
8
+ import os
9
+ sys.path.insert(0, os.path.dirname(__file__))
10
+
11
+ from syncnet_pipeline import SyncNetPipeline
12
+
13
+ # Import safe utils with fallback
14
+ try:
15
+ from safe_syncnet_utils import safe_syncnet_inference, calculate_lse_metrics
16
+ except ImportError:
17
+ # Fallback implementation for testing
18
+ def safe_syncnet_inference(pipeline, video_path, audio_path=None, cache_dir=None):
19
+ return pipeline.inference(video_path=video_path, audio_path=audio_path, cache_dir=cache_dir)
20
+
21
+ def calculate_lse_metrics(pipeline, video_path, audio_path=None, cache_dir=None):
22
+ results = pipeline.inference(video_path=video_path, audio_path=audio_path, cache_dir=cache_dir)
23
+ offsets, confs, dists, max_conf, min_dist, _, has_face = results
24
+
25
+ if not has_face or not confs:
26
+ return 0.0, float('inf'), "NO_FACE"
27
+
28
+ quality = "GOOD" if max_conf > 3.5 and min_dist < 7.0 else "FAIR" if max_conf > 2.0 else "POOR"
29
+ return max_conf, min_dist, quality
30
+
31
+ # Configure logging
32
+ logging.basicConfig(
33
+ level=logging.INFO,
34
+ format="%(asctime)s [%(levelname)s] %(message)s"
35
+ )
36
+
37
+ def test_audio_none_handling():
38
+ """Test automatic audio extraction when audio_path=None."""
39
+ print("\n=== Testing audio_path=None handling ===")
40
+
41
+ # Initialize pipeline
42
+ pipeline = SyncNetPipeline(
43
+ {'s3fd_weights': '../weights/sfd_face.pth', 'syncnet_weights': '../weights/syncnet_v2.model'},
44
+ device='cuda'
45
+ )
46
+
47
+ # Test with audio_path=None (should automatically extract audio)
48
+ video_path = '../example/pair_0000_lipsynced.mp4'
49
+
50
+ try:
51
+ print(f"Testing inference with audio_path=None for: {video_path}")
52
+ results = pipeline.inference(
53
+ video_path=video_path,
54
+ audio_path=None, # This should now work!
55
+ cache_dir='../example/cache_test_none'
56
+ )
57
+
58
+ offsets, confs, dists, max_conf, min_dist, _, has_face = results
59
+
60
+ if has_face:
61
+ print(f"✅ SUCCESS: Auto audio extraction worked!")
62
+ print(f" LSE-C: {max_conf:.3f}")
63
+ print(f" LSE-D: {min_dist:.3f}")
64
+ else:
65
+ print("⚠️ No face detected, but no error occurred")
66
+
67
+ except Exception as e:
68
+ print(f"❌ FAILED: {str(e)}")
69
+
70
+ def test_safe_wrapper_functions():
71
+ """Test the safe wrapper functions."""
72
+ print("\n=== Testing Safe Wrapper Functions ===")
73
+
74
+ pipeline = SyncNetPipeline(
75
+ {'s3fd_weights': '../weights/sfd_face.pth', 'syncnet_weights': '../weights/syncnet_v2.model'},
76
+ device='cuda'
77
+ )
78
+
79
+ video_path = '../example/pair_0000_lipsynced.mp4'
80
+
81
+ try:
82
+ print("Testing safe_syncnet_inference...")
83
+ results = safe_syncnet_inference(
84
+ pipeline,
85
+ video_path,
86
+ audio_path=None,
87
+ cache_dir='../example/cache_test_safe'
88
+ )
89
+ print("✅ safe_syncnet_inference: SUCCESS")
90
+
91
+ print("Testing calculate_lse_metrics...")
92
+ lse_c, lse_d, quality = calculate_lse_metrics(
93
+ pipeline,
94
+ video_path,
95
+ audio_path=None,
96
+ cache_dir='../example/cache_test_metrics'
97
+ )
98
+ print(f"✅ calculate_lse_metrics: SUCCESS")
99
+ print(f" LSE-C: {lse_c:.3f}")
100
+ print(f" LSE-D: {lse_d:.3f}")
101
+ print(f" Quality: {quality}")
102
+
103
+ except Exception as e:
104
+ print(f"❌ Safe wrapper test FAILED: {str(e)}")
105
+
106
+ def test_error_cases():
107
+ """Test various error cases."""
108
+ print("\n=== Testing Error Cases ===")
109
+
110
+ pipeline = SyncNetPipeline(
111
+ {'s3fd_weights': '../weights/sfd_face.pth', 'syncnet_weights': '../weights/syncnet_v2.model'},
112
+ device='cuda'
113
+ )
114
+
115
+ # Test with non-existent file
116
+ try:
117
+ results = safe_syncnet_inference(
118
+ pipeline,
119
+ "non_existent_video.mp4",
120
+ audio_path=None
121
+ )
122
+ print("❌ Should have failed for non-existent file")
123
+ except FileNotFoundError:
124
+ print("✅ Correctly caught FileNotFoundError for non-existent video")
125
+ except Exception as e:
126
+ print(f"⚠️ Unexpected error: {str(e)}")
127
+
128
+ def main():
129
+ """Run all tests."""
130
+ print("SyncNet v0.2.2 Error Handling Test Suite")
131
+ print("=" * 50)
132
+
133
+ test_audio_none_handling()
134
+ test_safe_wrapper_functions()
135
+ test_error_cases()
136
+
137
+ print("\n" + "=" * 50)
138
+ print("Test suite completed!")
139
+
140
+ if __name__ == "__main__":
141
+ main()
@@ -0,0 +1,204 @@
1
+ Metadata-Version: 2.4
2
+ Name: syncnet-python
3
+ Version: 0.2.3
4
+ Summary: SyncNet: Audio-visual synchronization detection using deep learning. Updated version of https://github.com/joonson/syncnet_python for modern Python versions.
5
+ Author: SyncNet Python Contributors
6
+ Maintainer: SyncNet Python Contributors
7
+ License-Expression: MIT AND Apache-2.0
8
+ Project-URL: Homepage, https://github.com/nawta/SyncNet_py309_313
9
+ Project-URL: Repository, https://github.com/nawta/SyncNet_py309_313
10
+ Project-URL: Issues, https://github.com/nawta/SyncNet_py309_313/issues
11
+ Keywords: audio-visual,synchronization,deep-learning,pytorch,lip-sync,video-processing,computer-vision
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Classifier: Topic :: Multimedia :: Video
24
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
25
+ Requires-Python: >=3.9
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ License-File: LICENSE-APACHE
29
+ License-File: NOTICE
30
+ Requires-Dist: torch>=2.0.0
31
+ Requires-Dist: torchvision>=0.15.0
32
+ Requires-Dist: numpy>=1.24.0
33
+ Requires-Dist: scipy>=1.10.0
34
+ Requires-Dist: pandas>=2.0.0
35
+ Requires-Dist: scenedetect<0.7,>=0.6.0
36
+ Requires-Dist: opencv-contrib-python>=4.8.0
37
+ Requires-Dist: python-speech-features>=0.6
38
+ Requires-Dist: ffmpeg-python>=0.2.0
39
+ Provides-Extra: dev
40
+ Requires-Dist: pytest>=7.4.0; extra == "dev"
41
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
42
+ Requires-Dist: black>=23.0.0; extra == "dev"
43
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
44
+ Requires-Dist: mypy>=1.7.0; extra == "dev"
45
+ Requires-Dist: types-opencv-python; extra == "dev"
46
+ Requires-Dist: types-scipy; extra == "dev"
47
+ Dynamic: license-file
48
+
49
+ # syncnet-python
50
+
51
+ [![PyPI version](https://badge.fury.io/py/syncnet-python.svg)](https://badge.fury.io/py/syncnet-python)
52
+ [![Python](https://img.shields.io/pypi/pyversions/syncnet-python.svg)](https://pypi.org/project/syncnet-python/)
53
+ [![License: MIT AND Apache-2.0](https://img.shields.io/badge/License-MIT%20AND%20Apache--2.0-yellow.svg)](https://github.com/nawta/SyncNet_py309_313/blob/main/NOTICE)
54
+
55
+ A pip-installable SyncNet for Python 3.9 to 3.13 and PyTorch 2. It computes the confidence and minimum distance scores that talking-head and lip-sync papers report as LSE-C and LSE-D.
56
+
57
+ SyncNet (Chung and Zisserman, 2016) is a network that measures how well mouth movements in a video match the speech audio. This package wraps the original SyncNet model and its S3FD face detector in one Python class and one command. Given a video, it finds and tracks faces, crops each face track, and returns three numbers per track: the audio-video offset in frames, the SyncNet confidence (LSE-C, higher means better sync), and the minimum audio-video feature distance (LSE-D, lower means better sync).
58
+
59
+ ## Quickstart
60
+
61
+ ### 1. Install
62
+
63
+ ```bash
64
+ pip install syncnet-python
65
+ ```
66
+
67
+ You also need `ffmpeg` on your `PATH` (`brew install ffmpeg` or `sudo apt-get install ffmpeg`).
68
+
69
+ Use version 0.2.3 or later. Versions 0.2.2 and earlier accept scenedetect 0.7, which removed the `scenedetect.video_manager` module the pipeline imports, and then `from syncnet_python import SyncNetPipeline` silently gives `None`. Version 0.2.3 requires `scenedetect>=0.6,<0.7` and raises an `ImportError` with the underlying message if an import fails. If you must stay on 0.2.2, install it with `pip install syncnet-python==0.2.2 "scenedetect<0.7"`.
70
+
71
+ The package uses `opencv-contrib-python` for `cv2`. Since 0.2.3 it is the only OpenCV package the install pulls in. Versions up to 0.2.2 also installed `opencv-python` through `scenedetect[opencv]`; if you upgrade an old environment and `cv2` fails to import, run `pip uninstall opencv-python opencv-contrib-python` and then `pip install opencv-contrib-python`.
72
+
73
+ ### 2. Download the weights
74
+
75
+ The package does not include the model weights. Both files come from the Oxford VGG SyncNet page, the same URLs that the original repository's `download_model.sh` uses:
76
+
77
+ ```bash
78
+ mkdir -p weights
79
+ wget https://www.robots.ox.ac.uk/~vgg/software/lipsync/data/syncnet_v2.model -O weights/syncnet_v2.model
80
+ wget https://www.robots.ox.ac.uk/~vgg/software/lipsync/data/sfd_face.pth -O weights/sfd_face.pth
81
+ ```
82
+
83
+ The same two files are also in the [`weights/`](https://github.com/nawta/SyncNet_py309_313/tree/main/weights) folder of this repository. They are byte-identical to the Oxford files (SHA-256 `961e8696…5442` for `syncnet_v2.model` and `d54a87c2…c491` for `sfd_face.pth`).
84
+
85
+ ### 3. Python API
86
+
87
+ ```python
88
+ from syncnet_python import SyncNetPipeline
89
+
90
+ pipe = SyncNetPipeline(
91
+ {"s3fd_weights": "weights/sfd_face.pth", "syncnet_weights": "weights/syncnet_v2.model"},
92
+ device="cpu", # or "cuda"
93
+ )
94
+ offsets, confs, dists, best_conf, min_dist, s3fd_json, has_face = pipe.inference(
95
+ video_path="clip.mp4",
96
+ audio_path=None, # None uses the video's own audio track; or pass a .wav path
97
+ )
98
+ print("AV offset (frames):", offsets[0])
99
+ print("LSE-C (confidence):", round(best_conf, 3))
100
+ print("LSE-D (min distance):", round(min_dist, 3))
101
+ ```
102
+
103
+ `offsets`, `confs` and `dists` are lists with one entry per face track. `best_conf` is the largest confidence over all tracks and `min_dist` is the smallest distance over all tracks. For a video with one face these equal `confs[0]` and `dists[0]`. With several faces the two values can come from different tracks, so use the per-track lists if you need scores for one speaker.
104
+
105
+ `syncnet_python.calculate_lse_metrics(pipe, video_path)` returns `(lse_c, lse_d, quality_label)` from the same values.
106
+
107
+ ### 4. Command line
108
+
109
+ ```bash
110
+ syncnet-python clip.mp4 --device cpu -o results.json
111
+ ```
112
+
113
+ The command reads the weights from `weights/` in the current directory by default; change this with `--s3fd-weights` and `--syncnet-weights`. It prints the offset and confidence for each video and writes offset, confidence and minimum distance to the JSON file. The default device is `cuda`, so pass `--device cpu` on a machine without an NVIDIA GPU.
114
+
115
+ ### Tested setup
116
+
117
+ The examples above were run on 2026-10-06 on an Apple Silicon Mac (CPU), using [`example/video.avi`](https://github.com/nawta/SyncNet_py309_313/blob/main/example/video.avi) converted to MP4. Each run used a fresh environment. The OpenCV column gives the version of `opencv-contrib-python`. In the 0.2.3 runs it was the only OpenCV package installed; in the 0.2.2 run `opencv-python` was also installed at the same version.
118
+
119
+ | Package | Python | PyTorch | NumPy | OpenCV | scenedetect | Offset | LSE-C | LSE-D |
120
+ |---|---|---|---|---|---|---|---|---|
121
+ | 0.2.3 | 3.13 (arm64) | 2.14.1 | 2.5.3 | 5.0.0 | 0.6.7.1 | 1 | 4.529 | 9.237 |
122
+ | 0.2.3 | 3.10 (arm64) | 2.14.1 | 2.2.6 | 5.0.0 | 0.6.7.1 | 1 | 4.529 | 9.237 |
123
+ | 0.2.2 | 3.9 (x86_64 under Rosetta 2) | 2.2.2 | 1.26.4 | 4.11.0 | 0.6.7.1 | 1 | 4.524 | 9.291 |
124
+
125
+ The 0.2.3 rows used the wheel built from this repository with a plain install. The Python API, `calculate_lse_metrics` and the CLI gave the same values. The Python 3.9 interpreter was an x86_64 build running under Rosetta 2. PyTorch 2.2.2 is the newest release with macOS x86_64 wheels, and it does not work with NumPy 2, so that run needed `numpy<2`, `opencv-python<4.12` and `opencv-contrib-python<4.12` installed by hand. The full run on the 5.3-second clip took about 10 seconds on CPU.
126
+
127
+ ## Changes in 0.2.3
128
+
129
+ - Requires `scenedetect>=0.6,<0.7`, so a plain `pip install syncnet-python` works again.
130
+ - A failed import inside the package raises `ImportError` with the original message. Earlier versions set `SyncNetPipeline` and the other exports to `None`.
131
+ - The repository now holds the 0.2.2 code that was published on PyPI but not committed (`calculate_lse_metrics`, `audio_path=None`, `ffmpeg` error handling).
132
+ - Package metadata declares the license as `MIT AND Apache-2.0` and ships `LICENSE`, `LICENSE-APACHE` and `NOTICE`.
133
+
134
+ See [CHANGELOG.md](https://github.com/nawta/SyncNet_py309_313/blob/main/CHANGELOG.md) for earlier versions.
135
+
136
+ ## Comparison with joonson/syncnet_python
137
+
138
+ The original repository, [joonson/syncnet_python](https://github.com/joonson/syncnet_python), was updated by its author on 2026-04-17 (PR #78). This table compares that version with this package.
139
+
140
+ | | joonson/syncnet_python (2026-04) | syncnet-python 0.2.3 |
141
+ |---|---|---|
142
+ | Install | clone, then `conda env create -f environment.yml`; no `setup.py` or `pyproject.toml` | `pip install syncnet-python` |
143
+ | Python | 3.10 (pinned in `environment.yml`) | 3.9 to 3.13 (3.9, 3.10 and 3.13 tested above) |
144
+ | PyTorch | 2.5.1 (pinned) | `torch>=2.0.0` |
145
+ | scenedetect | 0.6.7.1 (pinned) | `>=0.6,<0.7` |
146
+ | Python API | `SyncNetInstance.evaluate()` and `extract_feature()` score a pre-cropped face clip; face detection, tracking and cropping run only through `run_pipeline.py` | `SyncNetPipeline(...).inference(video_path, audio_path)` runs face detection, tracking, cropping and scoring in one call |
147
+ | Command line | `run_pipeline.py`, `run_syncnet.py`, `run_visualise.py` run in sequence, plus `demo_syncnet.py` for pre-cropped clips | one `syncnet-python` command that runs detection, tracking, cropping and scoring |
148
+ | Output | offset, minimum distance and confidence written to the log; per-frame distances saved as `activesd.pckl` under `--data_dir` | values returned to Python, or written to JSON by the CLI |
149
+ | Weights | downloaded by `download_model.sh` | downloaded separately (see above) |
150
+ | Visualisation of the result | `run_visualise.py` | not included |
151
+
152
+ ## Errors this fixes
153
+
154
+ Before the April 2026 update, the original repository pinned `scenedetect==0.5.1` and used `np.int`. Users hit these two errors in `run_pipeline.py`:
155
+
156
+ ```
157
+ TypeError: 'tuple' object does not support item assignment
158
+ ```
159
+
160
+ This comes from scenedetect 0.5.1's `ContentDetector` running with newer OpenCV (upstream issues [#55](https://github.com/joonson/syncnet_python/issues/55) and [#69](https://github.com/joonson/syncnet_python/issues/69)). This package uses scenedetect 0.6.
161
+
162
+ ```
163
+ AttributeError: module 'numpy' has no attribute 'int'.
164
+ ```
165
+
166
+ This comes from `.astype(np.int)` in `detectors/s3fd/box_utils.py`. NumPy 1.24 removed `np.int`. This package uses `.astype(int)`.
167
+
168
+ ## Repository layout
169
+
170
+ The PyPI package contains only the `syncnet_python/` folder. Most of its files (`syncnet_pipeline.py`, `SyncNetInstance.py`, `SyncNetModel.py`, `detectors/` and the scripts named `run_syncnet_pipeline_on_*.py`) come from the SyncNet evaluation code in [MoChaBench](https://github.com/congwei1230/MoChaBench) (`eval-lipsync/script/`), which builds on the original repository. This package adds error handling around the `ffmpeg` calls in `syncnet_pipeline.py`, plus `cli.py`.
171
+
172
+ The `syncnet/` folder holds a separate refactor with configuration files, logging and batch helpers. It is in this repository only and pip does not install it. `scripts/` has example scripts, and `example/` has a short test video with its audio.
173
+
174
+ ## Credits
175
+
176
+ The SyncNet model, its pretrained weights and the original code are by Joon Son Chung and Andrew Zisserman ([joonson/syncnet_python](https://github.com/joonson/syncnet_python), [project page](https://www.robots.ox.ac.uk/~vgg/software/lipsync/)). The S3FD face detector weights (`sfd_face.pth`) are downloaded from the same page. The model, detector and pipeline files in `syncnet_python/` come from [MoChaBench](https://github.com/congwei1230/MoChaBench); [NOTICE](https://github.com/nawta/SyncNet_py309_313/blob/main/NOTICE) lists them.
177
+
178
+ ## Citation
179
+
180
+ If you use this code in your research, please cite the original paper:
181
+
182
+ ```bibtex
183
+ @InProceedings{Chung16a,
184
+ author = "Chung, J.~S. and Zisserman, A.",
185
+ title = "Out of time: automated lip sync in the wild",
186
+ booktitle = "Workshop on Multi-view Lip-reading, ACCV",
187
+ year = "2016",
188
+ }
189
+ ```
190
+
191
+ ## License
192
+
193
+ This repository uses two licenses. [NOTICE](https://github.com/nawta/SyncNet_py309_313/blob/main/NOTICE) lists which file falls under which.
194
+
195
+ - The original SyncNet code by Joon Son Chung and the code written for this repository are under the MIT License ([LICENSE](https://github.com/nawta/SyncNet_py309_313/blob/main/LICENSE)).
196
+ - The files taken from MoChaBench are under the Apache License 2.0 ([LICENSE-APACHE](https://github.com/nawta/SyncNet_py309_313/blob/main/LICENSE-APACHE)).
197
+
198
+ The model weights have their own terms. The Oxford VGG SyncNet page says: "The model can be used for research purposes under Creative Commons Attribution License." The MIT and Apache licenses above do not cover the weights.
199
+
200
+ ## Links
201
+
202
+ - Source and issues: https://github.com/nawta/SyncNet_py309_313
203
+ - PyPI: https://pypi.org/project/syncnet-python/
204
+ - Original SyncNet: https://github.com/joonson/syncnet_python
@@ -1,19 +1,23 @@
1
1
  syncnet_python/SyncNetInstance.py,sha256=V-RtWL4nN2CW5n56DkE0d6hcnet4hAs_OVMaMS1ih20,6227
2
2
  syncnet_python/SyncNetModel.py,sha256=6qk27paoyV39MTsVyu6K2sbbM-1SLU_2N1zbqm1eeYs,3575
3
- syncnet_python/__init__.py,sha256=BAgXJdworzKFgKVrUD7cncAhhKlrqF5nMSnOcpTUvjM,702
3
+ syncnet_python/__init__.py,sha256=4OhqOByDwnM2ZhqaE2y4L02kPr5VRhhCEVSLck9QxSs,1241
4
4
  syncnet_python/cli.py,sha256=YSQVVDChLkQ96gFRFqD7laQXqbrLC2b8SKaF-vc8FuA,3256
5
5
  syncnet_python/run_syncnet_pipeline_on_1example.py,sha256=7I8_jEgIFw-RUqCHU29LrIWIRP77lTUiH6MePOxsuWQ,1008
6
6
  syncnet_python/run_syncnet_pipeline_on_mocha_generation_on_mocha_bench.py,sha256=HJHGLgKpf21bG27_x1QD3MAhqtHey26Ujxb8s2aK-tA,5928
7
7
  syncnet_python/run_syncnet_pipeline_on_your_own_model_results.py,sha256=m-kz_DHhka_DywpBRWdxk-S0hrwqvCR16RiVQ7HUqDk,6003
8
- syncnet_python/syncnet_pipeline.py,sha256=FJwhJ9_brdlY73gSkVbKkdZm197pNkcc3FAKyr-ubpY,13263
8
+ syncnet_python/safe_syncnet_utils.py,sha256=viucLggg13AW5xAjns_s-jlqv4rzvuRED0Ydo99_RbY,5381
9
+ syncnet_python/syncnet_pipeline.py,sha256=G9msGO9JDzfCkLD4sBQ8SOlk9QfCEPqjb9mbVAl93SA,16410
10
+ syncnet_python/test_error_handling.py,sha256=i5ib1qEjbMUQg913r9plAdXYciQx2jmUjzuoXPvc5f4,4658
9
11
  syncnet_python/test_lse_metrics.py,sha256=H_4U2LN-Wussx_KABX5y5EO3QGnaVhKNMuTjLH0zNrE,2884
10
12
  syncnet_python/detectors/__init__.py,sha256=WLone-DTbvQUFleY93pmq7xomPDVjda9ATpZYcS6_sA,23
11
13
  syncnet_python/detectors/s3fd/__init__.py,sha256=MIJfIEsKFTGh8brmD3fBQg8JZAp57NtaTkY6_I5QZP0,2322
12
14
  syncnet_python/detectors/s3fd/box_utils.py,sha256=CWn46LMJKO1cdenI_IWxBbDriO2ueWTCl14Xp28fr-U,7235
13
15
  syncnet_python/detectors/s3fd/nets.py,sha256=BYPJq9UJ5bq5Q5RgP1j-NsFzO1gP3N0PYE1X19-4PZw,5891
14
- syncnet_python-0.2.1.dist-info/licenses/LICENSE,sha256=qwJOQjZqnGgzcgwg3VUkT2pGKwLyZr5nUOm0Gv7Zfog,1088
15
- syncnet_python-0.2.1.dist-info/METADATA,sha256=3l1AsKqZM6hI1bQKaj6zeThFgSUi-JPgsF1iF6Ct3PY,7747
16
- syncnet_python-0.2.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
17
- syncnet_python-0.2.1.dist-info/entry_points.txt,sha256=zPJrIl_ekAa31dHZNCoTHiII2k_m5GyMD5BEkMR6Ytk,59
18
- syncnet_python-0.2.1.dist-info/top_level.txt,sha256=OkvKpxwq9NzQSjjdD571umGrI3meW9kVleOV2N5Ua04,15
19
- syncnet_python-0.2.1.dist-info/RECORD,,
16
+ syncnet_python-0.2.3.dist-info/licenses/LICENSE,sha256=JMCE5BdW3pk3NVn8ksaNiLxEABgPjlLkW-3ERoLPhug,1170
17
+ syncnet_python-0.2.3.dist-info/licenses/LICENSE-APACHE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
18
+ syncnet_python-0.2.3.dist-info/licenses/NOTICE,sha256=rtNvKHi6F6xy8MOG15aetzhkOt8DqdPcswsqCb-msLs,2033
19
+ syncnet_python-0.2.3.dist-info/METADATA,sha256=wM7GvQfaJxBJ4JUtl_m8vyX5s2z2tEysI7UCCQq5QMk,13109
20
+ syncnet_python-0.2.3.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
21
+ syncnet_python-0.2.3.dist-info/entry_points.txt,sha256=zPJrIl_ekAa31dHZNCoTHiII2k_m5GyMD5BEkMR6Ytk,59
22
+ syncnet_python-0.2.3.dist-info/top_level.txt,sha256=OkvKpxwq9NzQSjjdD571umGrI3meW9kVleOV2N5Ua04,15
23
+ syncnet_python-0.2.3.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (80.9.0)
2
+ Generator: setuptools (84.0.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,6 +1,7 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2024 SyncNet Python 3.13 Contributors
3
+ Copyright (c) 2016-present Joon Son Chung (original SyncNet code)
4
+ Copyright (c) 2024 SyncNet Python 3.13 Contributors (modifications)
4
5
 
5
6
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
7
  of this software and associated documentation files (the "Software"), to deal
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,43 @@
1
+ syncnet-python
2
+ https://github.com/nawta/SyncNet_py309_313
3
+
4
+ This repository contains code under two licenses.
5
+
6
+ 1. MIT License (see LICENSE)
7
+ The original SyncNet code by Joon Son Chung
8
+ (https://github.com/joonson/syncnet_python) and the code written for
9
+ this repository: syncnet_python/__init__.py, syncnet_python/cli.py,
10
+ syncnet_python/safe_syncnet_utils.py,
11
+ syncnet_python/test_error_handling.py,
12
+ syncnet_python/test_lse_metrics.py, and the syncnet/, scripts/ and
13
+ config/ folders.
14
+
15
+ 2. Apache License 2.0 (see LICENSE-APACHE)
16
+ The following files come from MoChaBench
17
+ (https://github.com/congwei1230/MoChaBench, folder eval-lipsync/script/),
18
+ which is distributed under the Apache License 2.0. MoChaBench's LICENSE
19
+ file does not name a copyright holder; the files are credited here to
20
+ the MoChaBench authors. MoChaBench's versions are in turn based on the
21
+ original SyncNet code above. All files in this list except
22
+ syncnet_pipeline.py are unchanged copies of MoChaBench's files.
23
+
24
+ syncnet_python/syncnet_pipeline.py (modified by nawta; the file
25
+ header lists the changes)
26
+ syncnet_python/SyncNetInstance.py
27
+ syncnet_python/SyncNetModel.py
28
+ syncnet_python/detectors/__init__.py
29
+ syncnet_python/detectors/s3fd/__init__.py
30
+ syncnet_python/detectors/s3fd/box_utils.py
31
+ syncnet_python/detectors/s3fd/nets.py
32
+ syncnet_python/run_syncnet_pipeline_on_1example.py
33
+ syncnet_python/run_syncnet_pipeline_on_mocha_generation_on_mocha_bench.py
34
+ syncnet_python/run_syncnet_pipeline_on_your_own_model_results.py
35
+
36
+ Model weights
37
+
38
+ weights/syncnet_v2.model and weights/sfd_face.pth are copies of the files
39
+ published by the Visual Geometry Group, University of Oxford, at
40
+ https://www.robots.ox.ac.uk/~vgg/software/lipsync/. That page states:
41
+ "The model can be used for research purposes under Creative Commons
42
+ Attribution License." Neither the MIT License nor the Apache License 2.0
43
+ above applies to these files.
@@ -1,217 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: syncnet-python
3
- Version: 0.2.1
4
- Summary: SyncNet: Audio-visual synchronization detection using deep learning. Updated version of https://github.com/joonson/syncnet_python for modern Python versions.
5
- Author: SyncNet Python Contributors
6
- Maintainer: SyncNet Python Contributors
7
- License: MIT
8
- Project-URL: Homepage, https://github.com/nawta/SyncNet_py313
9
- Project-URL: Bug Reports, https://github.com/nawta/SyncNet_py313/issues
10
- Project-URL: Source, https://github.com/nawta/SyncNet_py313
11
- Keywords: audio-visual,synchronization,deep-learning,pytorch,lip-sync,video-processing,computer-vision
12
- Classifier: Development Status :: 4 - Beta
13
- Classifier: Intended Audience :: Science/Research
14
- Classifier: Intended Audience :: Developers
15
- Classifier: License :: OSI Approved :: MIT License
16
- Classifier: Operating System :: OS Independent
17
- Classifier: Programming Language :: Python :: 3
18
- Classifier: Programming Language :: Python :: 3.9
19
- Classifier: Programming Language :: Python :: 3.10
20
- Classifier: Programming Language :: Python :: 3.11
21
- Classifier: Programming Language :: Python :: 3.12
22
- Classifier: Programming Language :: Python :: 3.13
23
- Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
- Classifier: Topic :: Multimedia :: Video
25
- Classifier: Topic :: Scientific/Engineering :: Image Processing
26
- Requires-Python: >=3.9
27
- Description-Content-Type: text/markdown
28
- License-File: LICENSE
29
- Requires-Dist: torch>=2.0.0
30
- Requires-Dist: torchvision>=0.15.0
31
- Requires-Dist: numpy>=1.24.0
32
- Requires-Dist: scipy>=1.10.0
33
- Requires-Dist: pandas>=2.0.0
34
- Requires-Dist: scenedetect[opencv]>=0.6.0
35
- Requires-Dist: opencv-contrib-python>=4.8.0
36
- Requires-Dist: python-speech-features>=0.6
37
- Requires-Dist: ffmpeg-python>=0.2.0
38
- Provides-Extra: dev
39
- Requires-Dist: pytest>=7.4.0; extra == "dev"
40
- Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
41
- Requires-Dist: black>=23.0.0; extra == "dev"
42
- Requires-Dist: ruff>=0.1.0; extra == "dev"
43
- Requires-Dist: mypy>=1.7.0; extra == "dev"
44
- Requires-Dist: types-opencv-python; extra == "dev"
45
- Requires-Dist: types-scipy; extra == "dev"
46
- Dynamic: license-file
47
-
48
- # SyncNet Python
49
-
50
- [![PyPI version](https://badge.fury.io/py/syncnet-python.svg)](https://badge.fury.io/py/syncnet-python)
51
- [![Python](https://img.shields.io/pypi/pyversions/syncnet-python.svg)](https://pypi.org/project/syncnet-python/)
52
- [![Downloads](https://pepy.tech/badge/syncnet-python)](https://pepy.tech/project/syncnet-python)
53
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
54
-
55
- Audio-visual synchronization detection using deep learning with modern Python architecture.
56
-
57
- This is a **refactored and enhanced version** of the original [SyncNet implementation](https://github.com/joonson/syncnet_python) by Joon Son Chung, updated for Python 3.9+ with clean architecture, comprehensive error handling, and performance optimizations.
58
-
59
- ## Overview
60
-
61
- SyncNet Python is a PyTorch implementation of the SyncNet model, which detects audio-visual synchronization in videos. It can identify lip-sync errors by analyzing the correspondence between mouth movements and spoken audio.
62
-
63
- ## Features
64
-
65
- ### Core Functionality
66
- - 🎥 **Audio-Visual Sync Detection**: Accurately detect synchronization between audio and video
67
- - 🔍 **Face Detection**: Automatic face detection and tracking using S3FD
68
- - 📊 **Detailed Analysis**: Per-crop offsets, confidence scores, and minimum distances
69
- - 🚀 **Batch Processing**: Process multiple videos efficiently
70
- - 🐍 **Python API**: Easy-to-use Python interface with proper error handling
71
-
72
- ### Architecture Improvements
73
- - 🏗️ **Clean Architecture**: Abstract base classes and factory patterns
74
- - ⚡ **Performance Optimized**: Parallel processing and memory management
75
- - 🛡️ **Robust Error Handling**: Comprehensive exception hierarchy
76
- - ⚙️ **Configuration Management**: YAML/JSON configuration support
77
- - 📝 **Advanced Logging**: Structured logging with progress tracking
78
- - 🔄 **Backward Compatibility**: Maintains compatibility with original API
79
-
80
- ## Installation
81
-
82
- ```bash
83
- pip install syncnet-python
84
- ```
85
-
86
- ### Additional Requirements
87
-
88
- 1. **FFmpeg**: Required for video processing
89
- ```bash
90
- # Ubuntu/Debian
91
- sudo apt-get install ffmpeg
92
-
93
- # macOS
94
- brew install ffmpeg
95
- ```
96
-
97
- 2. **Model Weights**: Download pre-trained weights
98
- - Download `sfd_face.pth` and `syncnet_v2.model`
99
- - Place them in a `weights/` directory
100
-
101
- ## Quick Start
102
-
103
- ```python
104
- from syncnet_python import SyncNetPipeline
105
-
106
- # Initialize pipeline
107
- pipeline = SyncNetPipeline(
108
- s3fd_weights="weights/sfd_face.pth",
109
- syncnet_weights="weights/syncnet_v2.model",
110
- device="cuda" # or "cpu"
111
- )
112
-
113
- # Process video
114
- results = pipeline.inference(
115
- video_path="video.mp4",
116
- audio_path=None # Extract from video
117
- )
118
-
119
- # Extract results (returns tuple)
120
- offset_list, confidence_list, min_dist_list, best_confidence, best_min_dist, detections_json, success = results
121
-
122
- # Get best results
123
- offset = offset_list[0] # AV offset in frames
124
- confidence = confidence_list[0] # Confidence score
125
- min_distance = min_dist_list[0] # Minimum distance
126
-
127
- print(f"AV Offset: {offset} frames")
128
- print(f"Confidence: {confidence:.3f}")
129
- print(f"Min Distance: {min_distance:.3f}")
130
- ```
131
-
132
- ### Detailed Analysis
133
-
134
- ```python
135
- # For detailed per-crop analysis
136
- for i, (offset, conf, dist) in enumerate(zip(offset_list, confidence_list, min_dist_list)):
137
- print(f"Crop {i+1}: offset={offset}, confidence={conf:.3f}, min_dist={dist:.3f}")
138
-
139
- # Parse face detections
140
- import json
141
- detections = json.loads(detections_json)
142
- print(f"Total frames with face detection: {len(detections)}")
143
- ```
144
-
145
- ## Command Line Usage
146
-
147
- ```bash
148
- # Process single video
149
- syncnet-python video.mp4
150
-
151
- # Process multiple videos
152
- syncnet-python video1.mp4 video2.mp4 --output results.json
153
-
154
- # Use CPU instead of GPU
155
- syncnet-python video.mp4 --device cpu
156
- ```
157
-
158
- ## Performance
159
-
160
- Tested with example files:
161
- - **Processing Speed**: 191.4 fps
162
- - **Face Detection**: 100% success rate
163
- - **Accuracy**: Detects 1-frame offsets with high confidence (4.5+)
164
- - **Compute Time**: ~0.65 seconds for 134 frames
165
-
166
- ## Architecture
167
-
168
- ### Refactored Core Modules
169
- - `syncnet/core/` - Modern refactored implementation
170
- - `base.py` - Abstract base classes and interfaces
171
- - `models.py` - Enhanced SyncNet model with factory pattern
172
- - `audio.py` - MFCC audio processing with streaming support
173
- - `video.py` - Parallel video processing with OpenCV
174
- - `sync_analyzer.py` - Optimized sync analysis with caching
175
- - `config.py` - Configuration management system
176
- - `exceptions.py` - Comprehensive error handling
177
- - `logging.py` - Advanced logging with progress tracking
178
- - `utils.py` - Memory management and utility functions
179
-
180
- ### Legacy Compatibility
181
- - `syncnet_python/` - Maintains original API compatibility
182
- - Full backward compatibility with existing code
183
-
184
- ## Requirements
185
-
186
- - Python 3.9+ (tested on 3.13)
187
- - PyTorch 2.0+
188
- - CUDA (optional but recommended)
189
- - FFmpeg
190
- - Additional dependencies: OpenCV, SciPy, NumPy, pandas
191
-
192
- ## Credits
193
-
194
- This package is based on the original [SyncNet implementation](https://github.com/joonson/syncnet_python) by Joon Son Chung, enhanced with modern Python architecture and performance optimizations.
195
-
196
- ## Citation
197
-
198
- If you use this code in your research, please cite the original paper:
199
-
200
- ```bibtex
201
- @inproceedings{chung2016out,
202
- title={Out of time: automated lip sync in the wild},
203
- author={Chung, Joon Son and Zisserman, Andrew},
204
- booktitle={Asian Conference on Computer Vision},
205
- year={2016}
206
- }
207
- ```
208
-
209
- ## License
210
-
211
- MIT License - see LICENSE file for details.
212
-
213
- ## Links
214
-
215
- - GitHub: https://github.com/yourusername/syncnet-python
216
- - Documentation: https://syncnet-python.readthedocs.io
217
- - Issues: https://github.com/yourusername/syncnet-python/issues