mkv-episode-matcher 0.1.13__py3-none-any.whl → 0.3.0__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.

Potentially problematic release.


This version of mkv-episode-matcher might be problematic. Click here for more details.

@@ -10,7 +10,6 @@ from mkv_episode_matcher.config import get_config, set_config
10
10
  logger.info("Starting the application")
11
11
 
12
12
 
13
-
14
13
  # Check if the configuration directory exists, if not create it
15
14
  if not os.path.exists(os.path.join(os.path.expanduser("~"), ".mkv-episode-matcher")):
16
15
  os.makedirs(os.path.join(os.path.expanduser("~"), ".mkv-episode-matcher"))
@@ -31,10 +30,16 @@ if not os.path.exists(log_dir):
31
30
  os.mkdir(log_dir)
32
31
 
33
32
  # Add a new handler for stdout logs
34
- logger.add(os.path.join(log_dir,"stdout.log"), format="{time} {level} {message}", level="DEBUG", rotation="10 MB")
33
+ logger.add(
34
+ os.path.join(log_dir, "stdout.log"),
35
+ format="{time} {level} {message}",
36
+ level="DEBUG",
37
+ rotation="10 MB",
38
+ )
35
39
 
36
40
  # Add a new handler for error logs
37
- logger.add(os.path.join(log_dir,"stderr.log"), level="ERROR", rotation="10 MB")
41
+ logger.add(os.path.join(log_dir, "stderr.log"), level="ERROR", rotation="10 MB")
42
+
38
43
 
39
44
  @logger.catch
40
45
  def main():
@@ -55,7 +60,6 @@ def main():
55
60
  The function logs its progress to two separate log files: one for standard output and one for errors.
56
61
  """
57
62
 
58
-
59
63
  # Parse command-line arguments
60
64
  parser = argparse.ArgumentParser(description="Process shows with TMDb API")
61
65
  parser.add_argument("--tmdb-api-key", help="TMDb API key")
@@ -0,0 +1,208 @@
1
+ # mkv_episode_matcher/episode_identification.py
2
+
3
+ import os
4
+ import glob
5
+ from pathlib import Path
6
+ from rapidfuzz import fuzz
7
+ from collections import defaultdict
8
+ import re
9
+ from loguru import logger
10
+ import json
11
+ import shutil
12
+
13
+ class EpisodeMatcher:
14
+ def __init__(self, cache_dir, min_confidence=0.6):
15
+ self.cache_dir = Path(cache_dir)
16
+ self.min_confidence = min_confidence
17
+ self.whisper_segments = None
18
+ self.series_name = None
19
+
20
+ def clean_text(self, text):
21
+ """Clean text by removing stage directions and normalizing repeated words."""
22
+ # Remove stage directions like [groans] and <i>SHIP:</i>
23
+ text = re.sub(r'\[.*?\]|\<.*?\>', '', text)
24
+ # Remove repeated words with dashes (e.g., "Y-y-you" -> "you")
25
+ text = re.sub(r'([A-Za-z])-\1+', r'\1', text)
26
+ # Remove multiple spaces
27
+ text = ' '.join(text.split())
28
+ return text.lower()
29
+
30
+ def chunk_score(self, whisper_chunk, ref_chunk):
31
+ """Calculate fuzzy match score between two chunks of text."""
32
+ whisper_clean = self.clean_text(whisper_chunk)
33
+ ref_clean = self.clean_text(ref_chunk)
34
+
35
+ # Use token sort ratio to handle word order differences
36
+ token_sort = fuzz.token_sort_ratio(whisper_clean, ref_clean)
37
+ # Use partial ratio to catch substring matches
38
+ partial = fuzz.partial_ratio(whisper_clean, ref_clean)
39
+
40
+ # Weight token sort more heavily but consider partial matches
41
+ return (token_sort * 0.7 + partial * 0.3) / 100.0
42
+
43
+ def identify_episode(self, video_file, temp_dir):
44
+ """Identify which episode matches this video file."""
45
+
46
+ # Get series name from parent directory
47
+ self.series_name = Path(video_file).parent.parent.name
48
+
49
+ # Load whisper transcript if not already processed
50
+ segments_file = Path(temp_dir) / f"{Path(video_file).stem}.segments.json"
51
+ if not segments_file.exists():
52
+ logger.error(f"No transcript found for {video_file}. Run speech recognition first.")
53
+ return None
54
+
55
+ with open(segments_file) as f:
56
+ self.whisper_segments = json.load(f)
57
+
58
+ # Get reference directory for this series
59
+ reference_dir = self.cache_dir / "data" / self.series_name
60
+ if not reference_dir.exists():
61
+ logger.error(f"No reference files found for {self.series_name}")
62
+ return None
63
+
64
+ # Match against reference files
65
+ match = self.match_all_references(reference_dir)
66
+
67
+ if match and match['confidence'] >= self.min_confidence:
68
+ # Extract season and episode from filename
69
+ match_file = Path(match['file'])
70
+ season_ep = re.search(r'S(\d+)E(\d+)', match_file.stem)
71
+ if season_ep:
72
+ season, episode = map(int, season_ep.groups())
73
+ return {
74
+ 'season': season,
75
+ 'episode': episode,
76
+ 'confidence': match['confidence'],
77
+ 'reference_file': str(match_file),
78
+ 'chunk_scores': match['chunk_scores']
79
+ }
80
+
81
+ return None
82
+
83
+ def match_all_references(self, reference_dir):
84
+ """Process all reference files and track matching scores."""
85
+ results = defaultdict(list)
86
+ best_match = None
87
+ best_confidence = 0
88
+
89
+ def process_chunks(ref_segments, filename):
90
+ nonlocal best_match, best_confidence
91
+
92
+ chunk_size = 300 # 5 minute chunks
93
+ whisper_chunks = defaultdict(list)
94
+ ref_chunks = defaultdict(list)
95
+
96
+ # Group segments into time chunks
97
+ for seg in self.whisper_segments:
98
+ chunk_idx = int(float(seg['start']) // chunk_size)
99
+ whisper_chunks[chunk_idx].append(seg['text'])
100
+
101
+ for seg in ref_segments:
102
+ chunk_idx = int(seg['start'] // chunk_size)
103
+ ref_chunks[chunk_idx].append(seg['text'])
104
+
105
+ # Score each chunk
106
+ for chunk_idx in whisper_chunks:
107
+ whisper_text = ' '.join(whisper_chunks[chunk_idx])
108
+
109
+ # Look for matching reference chunk and adjacent chunks
110
+ scores = []
111
+ for ref_idx in range(max(0, chunk_idx-1), chunk_idx+2):
112
+ if ref_idx in ref_chunks:
113
+ ref_text = ' '.join(ref_chunks[ref_idx])
114
+ score = self.chunk_score(whisper_text, ref_text)
115
+ scores.append(score)
116
+
117
+ if scores:
118
+ chunk_confidence = max(scores)
119
+ logger.info(f"File: {filename}, "
120
+ f"Time: {chunk_idx*chunk_size}-{(chunk_idx+1)*chunk_size}s, "
121
+ f"Confidence: {chunk_confidence:.2f}")
122
+
123
+ results[filename].append({
124
+ 'chunk_idx': chunk_idx,
125
+ 'confidence': chunk_confidence
126
+ })
127
+
128
+ # Early exit if we find a very good match
129
+ if chunk_confidence > self.min_confidence:
130
+ chunk_scores = results[filename]
131
+ confidence = sum(c['confidence'] * (0.9 ** c['chunk_idx'])
132
+ for c in chunk_scores) / len(chunk_scores)
133
+
134
+ if confidence > best_confidence:
135
+ best_confidence = confidence
136
+ best_match = {
137
+ 'file': filename,
138
+ 'confidence': confidence,
139
+ 'chunk_scores': chunk_scores
140
+ }
141
+ return True
142
+
143
+ return False
144
+
145
+ # Process each reference file
146
+ for ref_file in glob.glob(os.path.join(reference_dir, "*.srt")):
147
+ ref_segments = self.parse_srt_to_segments(ref_file)
148
+ filename = os.path.basename(ref_file)
149
+
150
+ if process_chunks(ref_segments, filename):
151
+ break
152
+
153
+ # If no early match found, find best overall match
154
+ if not best_match:
155
+ for filename, chunks in results.items():
156
+ # Weight earlier chunks more heavily
157
+ confidence = sum(c['confidence'] * (0.9 ** c['chunk_idx'])
158
+ for c in chunks) / len(chunks)
159
+
160
+ if confidence > best_confidence:
161
+ best_confidence = confidence
162
+ best_match = {
163
+ 'file': filename,
164
+ 'confidence': confidence,
165
+ 'chunk_scores': chunks
166
+ }
167
+
168
+ return best_match
169
+
170
+ def parse_srt_to_segments(self, srt_file):
171
+ """Parse SRT file into list of segments with start/end times and text."""
172
+ segments = []
173
+ current_segment = {}
174
+
175
+ with open(srt_file, 'r', encoding='utf-8') as f:
176
+ lines = f.readlines()
177
+
178
+ i = 0
179
+ while i < len(lines):
180
+ line = lines[i].strip()
181
+
182
+ if line.isdigit(): # Index
183
+ if current_segment:
184
+ segments.append(current_segment)
185
+ current_segment = {}
186
+
187
+ elif '-->' in line: # Timestamp
188
+ start, end = line.split(' --> ')
189
+ current_segment['start'] = self.timestr_to_seconds(start)
190
+ current_segment['end'] = self.timestr_to_seconds(end)
191
+
192
+ elif line: # Text
193
+ if 'text' in current_segment:
194
+ current_segment['text'] += ' ' + line
195
+ else:
196
+ current_segment['text'] = line
197
+
198
+ i += 1
199
+
200
+ if current_segment:
201
+ segments.append(current_segment)
202
+
203
+ return segments
204
+
205
+ def timestr_to_seconds(self, timestr):
206
+ """Convert SRT timestamp to seconds."""
207
+ h, m, s = timestr.replace(',','.').split(':')
208
+ return float(h) * 3600 + float(m) * 60 + float(s)
@@ -1,261 +1,117 @@
1
- # episode_matcher.py
2
- import os
3
- import re
1
+ # mkv_episode_matcher/episode_matcher.py
4
2
 
3
+ from pathlib import Path
4
+ import shutil
5
+ import glob
6
+ import os
5
7
  from loguru import logger
6
8
 
7
- from mkv_episode_matcher.__main__ import CACHE_DIR, CONFIG_FILE
9
+ from mkv_episode_matcher.__main__ import CONFIG_FILE, CACHE_DIR
8
10
  from mkv_episode_matcher.config import get_config
9
11
  from mkv_episode_matcher.mkv_to_srt import convert_mkv_to_srt
10
12
  from mkv_episode_matcher.tmdb_client import fetch_show_id
11
- from mkv_episode_matcher.utils import check_filename, cleanup_ocr_files, get_subtitles,clean_text
12
-
13
+ from mkv_episode_matcher.utils import (
14
+ check_filename,
15
+ clean_text,
16
+ cleanup_ocr_files,
17
+ get_subtitles,
18
+ process_reference_srt_files,
19
+ process_srt_files,
20
+ compare_and_rename_files,get_valid_seasons
21
+ )
22
+ from mkv_episode_matcher.speech_to_text import process_speech_to_text
23
+ from mkv_episode_matcher.episode_identification import EpisodeMatcher
13
24
 
14
- # hash_data = {}
15
- @logger.catch
16
25
  def process_show(season=None, dry_run=False, get_subs=False):
17
- """
18
- Process the show by downloading episode images and finding matching episodes.
19
- Args:
20
- season (int, optional): The season number to process. If provided, only that season will be processed. Defaults to None.
21
- dry_run (bool, optional): Whether to perform a dry run without actually processing the episodes. Defaults to False.
22
- get_subs (bool, optional): Whether to download subtitles for the episodes. Defaults to False.
23
- """
26
+ """Process the show using both speech recognition and OCR fallback."""
24
27
  config = get_config(CONFIG_FILE)
25
28
  show_dir = config.get("show_dir")
26
- show_name = clean_text(os.path.basename(show_dir))
27
- logger.info(f"Processing show '{show_name}'...")
28
29
 
29
- show_id = fetch_show_id(show_name)
30
- if show_id is None:
31
- logger.error(f"Could not find show '{os.path.basename(show_dir)}' on TMDb.")
32
- return
33
-
34
- # Get all season directories
35
- season_paths = [
36
- os.path.join(show_dir, d)
37
- for d in os.listdir(show_dir)
38
- if os.path.isdir(os.path.join(show_dir, d))
39
- ]
40
-
41
- # Filter seasons to only include those with .mkv files
42
- valid_season_paths = []
43
- for season_path in season_paths:
44
- mkv_files = [
45
- f for f in os.listdir(season_path)
46
- if f.endswith(".mkv")
47
- ]
48
- if mkv_files:
49
- valid_season_paths.append(season_path)
50
-
51
- if not valid_season_paths:
52
- logger.warning(f"No seasons with .mkv files found in show '{show_name}'")
30
+ # Initialize episode matcher
31
+ matcher = EpisodeMatcher(CACHE_DIR)
32
+
33
+ # Get valid season directories
34
+ season_paths = get_valid_seasons(show_dir)
35
+ if not season_paths:
36
+ logger.warning(f"No seasons with .mkv files found")
53
37
  return
54
38
 
55
- logger.info(
56
- f"Found {len(valid_season_paths)} seasons with .mkv files for show '{show_name}'"
57
- )
58
-
59
- # Extract season numbers from valid paths
60
- seasons_to_process = [
61
- int(os.path.basename(season_path).split()[-1])
62
- for season_path in valid_season_paths
63
- ]
64
-
65
- if get_subs:
66
- get_subtitles(show_id, seasons=set(seasons_to_process))
67
-
68
39
  if season is not None:
69
- # If specific season requested, check if it has .mkv files
70
40
  season_path = os.path.join(show_dir, f"Season {season}")
71
- if season_path not in valid_season_paths:
41
+ if season_path not in season_paths:
72
42
  logger.warning(f"Season {season} has no .mkv files to process")
73
43
  return
74
-
75
- mkv_files = [
76
- os.path.join(season_path, f)
77
- for f in os.listdir(season_path)
78
- if f.endswith(".mkv")
79
- ]
80
- else:
81
- # Process all valid seasons
82
- for season_path in valid_season_paths:
83
- mkv_files = [
84
- os.path.join(season_path, f)
85
- for f in os.listdir(season_path)
86
- if f.endswith(".mkv")
87
- ]
88
- # Filter out files that have already been processed
89
- for f in mkv_files:
90
- if check_filename(f):
91
- logger.info(f"Skipping {f}, already processed")
92
- mkv_files.remove(f)
93
- if len(mkv_files) == 0:
94
- logger.info("No new files to process")
95
- return
96
- convert_mkv_to_srt(season_path, mkv_files)
97
- reference_text_dict = process_reference_srt_files(show_name)
98
- srt_text_dict = process_srt_files(show_dir)
99
- compare_and_rename_files(srt_text_dict, reference_text_dict, dry_run=dry_run)
100
- cleanup_ocr_files(show_dir)
101
-
102
- def check_filename(filename):
103
- """
104
- Check if the filename is in the correct format.
105
-
106
- Args:
107
- filename (str): The filename to check.
108
-
109
- Returns:
110
- bool: True if the filename is in the correct format, False otherwise.
111
- """
112
- # Check if the filename matches the expected format
113
- match = re.match(r".*S\d+E\d+", filename)
114
- return bool(match)
115
- def extract_srt_text(filepath):
116
- """
117
- Extracts the text from an SRT file.
118
-
119
- Args:
120
- filepath (str): The path to the SRT file.
121
-
122
- Returns:
123
- list: A list of lists, where each inner list represents a block of text from the SRT file.
124
- Each inner list contains the lines of text for that block.
125
- """
126
- # extract the text from the file
127
- with open(filepath) as f:
128
- filepath = f.read()
129
- text_lines = [
130
- filepath.split("\n\n")[i].split("\n")[2:]
131
- for i in range(len(filepath.split("\n\n")))
132
- ]
133
- # remove empty lines
134
- text_lines = [[line for line in lines if line] for lines in text_lines]
135
- # remove <i> or </i> tags
136
- text_lines = [
137
- [re.sub(r"<i>|</i>|", "", line) for line in lines] for lines in text_lines
138
- ]
139
- # remove empty lists
140
- text_lines = [lines for lines in text_lines if lines]
141
- return text_lines
142
-
44
+ season_paths = [season_path]
143
45
 
144
- def compare_text(text1, text2):
145
- """
146
- Compare two lists of text lines and return the number of matching lines.
147
-
148
- Args:
149
- text1 (list): List of text lines from the first source.
150
- text2 (list): List of text lines from the second source.
151
-
152
- Returns:
153
- int: Number of matching lines between the two sources.
154
- """
155
- # Flatten the list of text lines
156
- flat_text1 = [line for lines in text1 for line in lines]
157
- flat_text2 = [line for lines in text2 for line in lines]
158
-
159
- # Compare the two lists of text lines
160
- matching_lines = set(flat_text1).intersection(flat_text2)
161
- return len(matching_lines)
162
-
163
-
164
- def extract_season_episode(filename):
165
- """
166
- Extract the season and episode number from the filename.
167
-
168
- Args:
169
- filename (str): The filename to extract the season and episode from.
170
-
171
- Returns:
172
- tuple: A tuple containing the season and episode number.
173
- """
174
- # Extract the season and episode number from the filename
175
- match = re.search(r"S(\d+)E(\d+)", filename)
176
- if match:
177
- season = int(match.group(1))
178
- episode = int(match.group(2))
179
- return season, episode
180
- else:
181
- return None, None
182
-
183
-
184
- def process_reference_srt_files(series_name):
185
- """
186
- Process reference SRT files for a given series.
187
-
188
- Args:
189
- series_name (str): The name of the series.
190
-
191
- Returns:
192
- dict: A dictionary containing the reference files where the keys are the MKV filenames
193
- and the values are the corresponding SRT texts.
194
- """
195
- reference_files = {}
196
- reference_dir = os.path.join(CACHE_DIR, "data", series_name)
197
- for dirpath, _, filenames in os.walk(reference_dir):
198
- for filename in filenames:
199
- if filename.lower().endswith(".srt"):
200
- srt_file = os.path.join(dirpath, filename)
201
- logger.info(f"Processing {srt_file}")
202
- srt_text = extract_srt_text(srt_file)
203
- season, episode = extract_season_episode(filename)
204
- mkv_filename = f"{series_name} - S{season:02}E{episode:02}.mkv"
205
- reference_files[mkv_filename] = srt_text
206
- return reference_files
207
-
208
-
209
- def process_srt_files(show_dir):
210
- """
211
- Process all SRT files in the given directory and its subdirectories.
212
-
213
- Args:
214
- show_dir (str): The directory path where the SRT files are located.
215
-
216
- Returns:
217
- dict: A dictionary containing the SRT file paths as keys and their corresponding text content as values.
218
- """
219
- srt_files = {}
220
- for dirpath, _, filenames in os.walk(show_dir):
221
- for filename in filenames:
222
- if filename.lower().endswith(".srt"):
223
- srt_file = os.path.join(dirpath, filename)
224
- logger.info(f"Processing {srt_file}")
225
- srt_text = extract_srt_text(srt_file)
226
- srt_files[srt_file] = srt_text
227
- return srt_files
228
-
229
-
230
- def compare_and_rename_files(srt_files, reference_files, dry_run=False):
231
- """
232
- Compare the srt files with the reference files and rename the matching mkv files.
233
-
234
- Args:
235
- srt_files (dict): A dictionary containing the srt files as keys and their contents as values.
236
- reference_files (dict): A dictionary containing the reference files as keys and their contents as values.
237
- dry_run (bool, optional): If True, the function will only log the renaming actions without actually renaming the files. Defaults to False.
238
- """
239
- logger.info(
240
- f"Comparing {len(srt_files)} srt files with {len(reference_files)} reference files"
241
- )
242
- for srt_text in srt_files.keys():
243
- parent_dir = os.path.dirname(os.path.dirname(srt_text))
244
- for reference in reference_files.keys():
245
- season, episode = extract_season_episode(reference)
246
- mkv_file = os.path.join(
247
- parent_dir, os.path.basename(srt_text).replace(".srt", ".mkv")
248
- )
249
- matching_lines = compare_text(
250
- reference_files[reference], srt_files[srt_text]
251
- )
252
- if matching_lines >= int(len(reference_files[reference]) * 0.1):
253
- logger.info(f"Matching lines: {matching_lines}")
254
- logger.info(f"Found matching file: {mkv_file} ->{reference}")
255
- new_filename = os.path.join(parent_dir, reference)
256
- if not os.path.exists(new_filename):
257
- if os.path.exists(mkv_file) and not dry_run:
258
- logger.info(f"Renaming {mkv_file} to {new_filename}")
259
- os.rename(mkv_file, new_filename)
46
+ # Process each season
47
+ for season_path in season_paths:
48
+ # Get MKV files that haven't been processed
49
+ mkv_files = [f for f in glob.glob(os.path.join(season_path, "*.mkv"))
50
+ if not check_filename(f)]
51
+
52
+ if not mkv_files:
53
+ logger.info(f"No new files to process in {season_path}")
54
+ continue
55
+
56
+ # Create temp directories
57
+ temp_dir = Path(season_path) / "temp"
58
+ ocr_dir = Path(season_path) / "ocr"
59
+ temp_dir.mkdir(exist_ok=True)
60
+ ocr_dir.mkdir(exist_ok=True)
61
+
62
+ try:
63
+ unmatched_files = []
64
+
65
+ # First pass: Try speech recognition matching
66
+ for mkv_file in mkv_files:
67
+ logger.info(f"Attempting speech recognition match for {mkv_file}")
68
+
69
+ # Extract audio and run speech recognition
70
+ process_speech_to_text(mkv_file, str(temp_dir))
71
+ match = matcher.identify_episode(mkv_file, temp_dir)
72
+
73
+ if match and match['confidence'] >= matcher.min_confidence:
74
+ # Rename the file
75
+ new_name = f"{matcher.series_name} - S{match['season']:02d}E{match['episode']:02d}.mkv"
76
+ new_path = os.path.join(season_path, new_name)
77
+
78
+ logger.info(f"Speech matched {os.path.basename(mkv_file)} to {new_name} "
79
+ f"(confidence: {match['confidence']:.2f})")
80
+
81
+ if not dry_run:
82
+ os.rename(mkv_file, new_path)
260
83
  else:
261
- logger.info(f"File {new_filename} already exists, skipping")
84
+ logger.info(f"Speech recognition match failed for {mkv_file}, will try OCR")
85
+ unmatched_files.append(mkv_file)
86
+
87
+ # Second pass: Try OCR for unmatched files
88
+ if unmatched_files:
89
+ logger.info(f"Attempting OCR matching for {len(unmatched_files)} unmatched files")
90
+
91
+ # Convert files to SRT using OCR
92
+ convert_mkv_to_srt(season_path, unmatched_files)
93
+
94
+ # Process OCR results
95
+ reference_text_dict = process_reference_srt_files(matcher.series_name)
96
+ srt_text_dict = process_srt_files(str(ocr_dir))
97
+
98
+ # Compare and rename
99
+ compare_and_rename_files(
100
+ srt_text_dict,
101
+ reference_text_dict,
102
+ dry_run=dry_run,
103
+ min_confidence=0.1 # Lower threshold for OCR
104
+ )
105
+
106
+ # Download subtitles if requested
107
+ if get_subs:
108
+ show_id = fetch_show_id(matcher.series_name)
109
+ if show_id:
110
+ seasons = {int(os.path.basename(p).split()[-1]) for p in season_paths}
111
+ get_subtitles(show_id, seasons=seasons)
112
+
113
+ finally:
114
+ # Cleanup
115
+ if not dry_run:
116
+ shutil.rmtree(temp_dir)
117
+ cleanup_ocr_files(show_dir)