ChapterRecognition.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/domain/ChapterRecognition.kt
1package eu.friedcutlet.yokan.domain23/**4 * Chapter / episode number recognition and missing chapter gap detection.5 *6 * Direct port and enhancement of Mangayomi's `lib/utils/chapter_recognition.dart`7 * (incorporating commits f1170d47, 4af383cb, and 96f1830a).8 *9 * Capabilities:10 * - Preserves decimal chapter precision (e.g. 12.5).11 * - Distinguishes unnumbered chapters (null, e.g. "Special", "Prologue") from genuine chapter 0.0.12 * - Detects missing chapter gaps (e.g. chapters 1, 2, 4, 5 present -> chapter 3 missing).13 * - Multi-season anime bucket sorting when numbering resets across seasons.14 */15object ChapterRecognition {16 fun rawSeasonAndNumber(mangaTitle: String, chapter: Chapter): Pair<Int, Double?> {17 val inferred = rawSeasonAndNumber(mangaTitle, chapter.numberingName?.takeIf(String::isNotBlank) ?: chapter.name)18 return (chapter.season?.takeIf { it >= 0 } ?: inferred.first) to19 (chapter.number?.takeIf { it.isFinite() && it >= 0 } ?: inferred.second)20 }2122 fun parseEpisodeNumber(mangaTitle: String, chapter: Chapter): Double = rawSeasonAndNumber(mangaTitle, chapter).second ?: 0.023 private val unwanted = Regex(24 "\\b(?:v|ver|vol|version|volume|season|staffel|saison|temporada|s)[^a-z]?[0-9]+",25 )26 private val unwantedWhiteSpace = Regex("\\s(?=extra|special|omake)")27 private val seasonKeyword = Regex(28 "\\b(?:staffel|season|saison|temporada|s)\\s*([0-9]+)",29 )30 private val episodeKeyword = Regex(31 "\\b(?:folge|episode|ep\\.?)\\s*([0-9]+(?:\\.[0-9]+)?)",32 )33 fun parseSeasonNumber(name: String): Int? = seasonKeyword.find(name.lowercase())?.groupValues?.get(1)?.toIntOrNull()34 // Lookbehind for "ch." followed by zero or more spaces.35 private val chNotation = Regex(36 "(?<=ch\\.) *([0-9]+)(\\.[0-9]+)?(\\.?[a-z]+)?",37 )38 private val bareNumber = Regex("([0-9]+)(\\.[0-9]+)?(\\.?[a-z]+)?")3940 /**41 * Sort key for the UI list. Encodes season into the result so42 * multi-season anime sorts correctly: `season * 100_000 + episode`.43 */44 fun parseChapterNumber(mangaTitle: String, chapterName: String): Double {45 val (season, ep) = rawSeasonAndNumber(mangaTitle, chapterName)46 return withSeason(season, ep ?: 0.0)47 }4849 /**50 * Episode number within a season — used for tracker updates51 * (MAL / AniList / Kitsu) and AniSkip lookups. The tracker entry is52 * already season-specific, so the season prefix is stripped.53 */54 fun parseEpisodeNumber(mangaTitle: String, chapterName: String): Double {55 val (_, ep) = rawSeasonAndNumber(mangaTitle, chapterName)56 return ep ?: 0.057 }5859 /**60 * The key that answers "are these two the same chapter / episode".61 *62 * Season is part of the answer. Without it, episode 1 of season 2 is the63 * same chapter as episode 1 of season 1, and whichever arrives second is64 * dropped before it reaches the library. A show with two seasons then65 * displays one of them.66 *67 * Null when the name carries no number at all, because "Special" and68 * "Prologue" are not all the same chapter either. Callers skip the69 * composite check in that case rather than folding them together.70 *71 * [scanlator] is omitted by callers deciding whether read state carries72 * over, since the same episode from a different group is still that episode.73 */74 fun chapterIdentityKey(75 mangaTitle: String?,76 chapterName: String?,77 scanlator: String? = null,78 ): String? {79 val title = mangaTitle.orEmpty()80 val name = chapterName?.takeIf { it.isNotBlank() } ?: return null81 val (season, ep) = rawSeasonAndNumber(title, name)82 if (ep == null || ep <= 0.0) return null83 return "$season::$ep::${scanlator.orEmpty()}"84 }8586 /**87 * Raw (season, episode) pair, unbucketed — season is 0 if none matched.88 * Episode keeps its fractional part (e.g. 12.5).89 * Episode is null when the name has no detectable number at all (e.g. "Special", "Prologue") —90 * distinct from a genuine chapter 0.0.91 */92 fun rawSeasonAndNumber(mangaTitle: String, chapterName: String): Pair<Int, Double?> {93 val name = chapterName94 .lowercase()95 .replace(mangaTitle.lowercase(), "")96 .trim()97 .replace(',', '.')98 .replace('-', '.')99 .replace(unwantedWhiteSpace, "")100101 val season = seasonKeyword.find(name)?.groupValues?.getOrNull(1)?.toIntOrNull() ?: 0102103 episodeKeyword.find(name)?.let { match ->104 val ep = match.groupValues.getOrNull(1)?.toDoubleOrNull()105 return season to ep106 }107108 // Strip season / volume noise, then look for ch.X or a bare number.109 val stripped = name.replace(unwanted, "")110 val ep = extractNumber(stripped)111 return season to ep112 }113114 /**115 * Sort/identity keys for chapters. Buckets by season only if numbering actually116 * repeats across seasons (collisions >= 3).117 * Returns a map of Chapter ID to sort key. A null key indicates an unnumbered chapter.118 */119 fun chapterSortKeys(mangaTitle: String, chapters: List<Chapter>): Map<Long, Double?> {120 val raw = chapters.associate { it.id to rawSeasonAndNumber(mangaTitle, it) }121 val episodeToSeasons = mutableMapOf<Double, MutableSet<Int>>()122123 for (pair in raw.values) {124 val ep = pair.second ?: continue125 episodeToSeasons.getOrPut(ep) { mutableSetOf() }.add(pair.first)126 }127128 val collisions = episodeToSeasons.values.count { it.size > 1 }129 val resets = collisions >= 3130131 return raw.mapValues { (_, pair) ->132 val ep = pair.second ?: return@mapValues null133 if (resets && pair.first > 0) {134 pair.first * 100_000.0 + ep135 } else {136 ep137 }138 }139 }140141 /**142 * Count of whole numbers missing from the recognized chapter sequence.143 * E.g. chapters 1, 2, 4, 5 present means 1 (chapter 3) is missing.144 * Decimal extras (12.5) are floored into their whole chapter.145 */146 fun missingChapterCount(mangaTitle: String, chapters: List<Chapter>): Int {147 val numbers = mutableSetOf<Int>()148 for (chapter in chapters) {149 val (_, ep) = rawSeasonAndNumber(mangaTitle, chapter)150 if (ep != null) {151 numbers.add(ep.toInt())152 }153 }154 if (numbers.size < 2) return 0155 val lowest = numbers.minOrNull() ?: return 0156 val highest = numbers.maxOrNull() ?: return 0157 val expectedCount = highest - lowest + 1158 return maxOf(0, expectedCount - numbers.size)159 }160161 /**162 * Number of chapters whose name has no detectable chapter/episode number at all163 * (e.g. "Special", "Prologue", "Extra").164 */165 fun unrecognizedChapterNumberCount(mangaTitle: String, chapters: List<Chapter>): Int {166 return chapters.count { chapter ->167 rawSeasonAndNumber(mangaTitle, chapter).second == null168 }169 }170171 private fun withSeason(season: Int, ep: Double): Double =172 if (season > 0) season * 100_000.0 + ep else ep173174 private fun extractNumber(name: String): Double? {175 chNotation.find(name)?.let { return fromMatch(it) }176 bareNumber.find(name)?.let { return fromMatch(it) }177 return null178 }179180 private fun fromMatch(match: MatchResult): Double {181 val groups = match.groupValues182 val base = groups.getOrNull(1)?.toDoubleOrNull() ?: return 0.0183 val decimal = groups.getOrNull(2)?.takeIf { it.isNotEmpty() }184 val alpha = groups.getOrNull(3)?.takeIf { it.isNotEmpty() }185 return base + decimalAddition(decimal, alpha)186 }187188 private fun decimalAddition(decimal: String?, alpha: String?): Double {189 if (!decimal.isNullOrEmpty()) return decimal.toDoubleOrNull() ?: 0.0190 if (!alpha.isNullOrEmpty()) {191 if ("extra" in alpha) return 0.99192 if ("omake" in alpha) return 0.98193 if ("special" in alpha) return 0.97194 val trimmed = alpha.removePrefix(".")195 if (trimmed.length == 1) return parseAlphaPostFix(trimmed[0])196 }197 return 0.0198 }199200 private fun parseAlphaPostFix(c: Char): Double {201 val number = c.code - ('a'.code - 1)202 if (number >= 10) return 0.0203 return number / 10.0204 }205}206