Karan Adhikari commited on
enhace matching (#62)
Browse files- Backend/helper/imdb.py +70 -15
- Backend/helper/metadata.py +410 -139
- Backend/helper/pyro.py +110 -37
Backend/helper/imdb.py
CHANGED
|
@@ -1,13 +1,31 @@
|
|
| 1 |
import httpx
|
| 2 |
import re
|
| 3 |
import asyncio
|
| 4 |
-
from typing import Optional, Dict, Any
|
| 5 |
|
| 6 |
BASE_URL = "https://v3-cinemeta.strem.io"
|
| 7 |
|
| 8 |
_client: Optional[httpx.AsyncClient] = None
|
| 9 |
_client_lock = asyncio.Lock()
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
async def _get_client() -> httpx.AsyncClient:
|
| 12 |
global _client
|
| 13 |
async with _client_lock:
|
|
@@ -18,6 +36,19 @@ async def _get_client() -> httpx.AsyncClient:
|
|
| 18 |
)
|
| 19 |
return _client
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
def extract_first_year(year_string) -> int:
|
| 22 |
if not year_string:
|
| 23 |
return 0
|
|
@@ -27,28 +58,51 @@ def extract_first_year(year_string) -> int:
|
|
| 27 |
return int(year_match.group(1))
|
| 28 |
return 0
|
| 29 |
|
|
|
|
| 30 |
async def search_title(query: str, type: str) -> Optional[Dict[str, Any]]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
client = await _get_client()
|
| 32 |
cinemeta_type = "series" if type == "tvSeries" else type
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
try:
|
| 36 |
resp = await client.get(url)
|
| 37 |
if resp.status_code != 200:
|
| 38 |
-
return
|
| 39 |
data = resp.json()
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
except Exception:
|
| 51 |
-
return
|
|
|
|
| 52 |
|
| 53 |
async def get_detail(imdb_id: str, media_type: str) -> Optional[Dict[str, Any]]:
|
| 54 |
client = await _get_client()
|
|
@@ -94,6 +148,7 @@ async def get_detail(imdb_id: str, media_type: str) -> Optional[Dict[str, Any]]:
|
|
| 94 |
except Exception:
|
| 95 |
return None
|
| 96 |
|
|
|
|
| 97 |
async def get_season(imdb_id: str, season_id: int, episode_id: int) -> Optional[Dict[str, Any]]:
|
| 98 |
client = await _get_client()
|
| 99 |
try:
|
|
|
|
| 1 |
import httpx
|
| 2 |
import re
|
| 3 |
import asyncio
|
| 4 |
+
from typing import Optional, Dict, Any, List
|
| 5 |
|
| 6 |
BASE_URL = "https://v3-cinemeta.strem.io"
|
| 7 |
|
| 8 |
_client: Optional[httpx.AsyncClient] = None
|
| 9 |
_client_lock = asyncio.Lock()
|
| 10 |
|
| 11 |
+
# Pre-compiled emoji / unicode-symbol strip pattern
|
| 12 |
+
_EMOJI_RE = re.compile(
|
| 13 |
+
"["
|
| 14 |
+
"\U0001F600-\U0001F64F" # emoticons
|
| 15 |
+
"\U0001F300-\U0001F5FF" # symbols & pictographs
|
| 16 |
+
"\U0001F680-\U0001F6FF" # transport & map
|
| 17 |
+
"\U0001F700-\U0001FAFF" # extended symbols
|
| 18 |
+
"\U00002702-\U000027B0" # dingbats
|
| 19 |
+
"\U000024C2-\U0001F251" # enclosed chars
|
| 20 |
+
"\u2600-\u26FF" # misc symbols
|
| 21 |
+
"\u2700-\u27BF" # dingbats block
|
| 22 |
+
"\uFE00-\uFE0F" # variation selectors
|
| 23 |
+
"\U0001F1E0-\U0001F1FF" # flags
|
| 24 |
+
"]+",
|
| 25 |
+
re.UNICODE,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
async def _get_client() -> httpx.AsyncClient:
|
| 30 |
global _client
|
| 31 |
async with _client_lock:
|
|
|
|
| 36 |
)
|
| 37 |
return _client
|
| 38 |
|
| 39 |
+
|
| 40 |
+
def _clean_search_query(query: str) -> str:
|
| 41 |
+
"""
|
| 42 |
+
Strip emojis, decorative unicode symbols and non-essential punctuation
|
| 43 |
+
from a search query so Cinemeta can find the title reliably.
|
| 44 |
+
"""
|
| 45 |
+
q = _EMOJI_RE.sub(" ", query)
|
| 46 |
+
# Keep word chars, spaces, hyphens, apostrophes, ampersands, colons
|
| 47 |
+
q = re.sub(r"[^\w\s\-\'&:.]", " ", q)
|
| 48 |
+
q = re.sub(r"\s+", " ", q).strip()
|
| 49 |
+
return q
|
| 50 |
+
|
| 51 |
+
|
| 52 |
def extract_first_year(year_string) -> int:
|
| 53 |
if not year_string:
|
| 54 |
return 0
|
|
|
|
| 58 |
return int(year_match.group(1))
|
| 59 |
return 0
|
| 60 |
|
| 61 |
+
|
| 62 |
async def search_title(query: str, type: str) -> Optional[Dict[str, Any]]:
|
| 63 |
+
"""
|
| 64 |
+
Return the single top Cinemeta result (backward-compatible).
|
| 65 |
+
Uses cleaned query to handle emojis / special chars in titles.
|
| 66 |
+
"""
|
| 67 |
+
results = await search_title_multi(query=query, type=type, limit=1)
|
| 68 |
+
return results[0] if results else None
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
async def search_title_multi(query: str, type: str, limit: int = 8) -> List[Dict[str, Any]]:
|
| 72 |
+
"""
|
| 73 |
+
Return up to *limit* Cinemeta results for *query*.
|
| 74 |
+
The caller is responsible for picking the best match via fuzzy scoring.
|
| 75 |
+
"""
|
| 76 |
client = await _get_client()
|
| 77 |
cinemeta_type = "series" if type == "tvSeries" else type
|
| 78 |
+
|
| 79 |
+
# Clean the query before sending – emojis break the URL match
|
| 80 |
+
cleaned = _clean_search_query(query)
|
| 81 |
+
normalized = ".".join(cleaned.strip().lower().split())
|
| 82 |
+
|
| 83 |
+
url = f"{BASE_URL}/catalog/{cinemeta_type}/imdb/search={normalized}.json"
|
| 84 |
try:
|
| 85 |
resp = await client.get(url)
|
| 86 |
if resp.status_code != 200:
|
| 87 |
+
return []
|
| 88 |
data = resp.json()
|
| 89 |
+
results: List[Dict[str, Any]] = []
|
| 90 |
+
if data and "metas" in data and data["metas"]:
|
| 91 |
+
for meta in data["metas"][:limit]:
|
| 92 |
+
imdb_id = meta.get("imdb_id") or meta.get("id", "")
|
| 93 |
+
if not imdb_id:
|
| 94 |
+
continue
|
| 95 |
+
results.append({
|
| 96 |
+
"id": imdb_id,
|
| 97 |
+
"type": type,
|
| 98 |
+
"title": meta.get("name", ""),
|
| 99 |
+
"year": meta.get("releaseInfo", ""),
|
| 100 |
+
"poster": meta.get("poster", ""),
|
| 101 |
+
})
|
| 102 |
+
return results
|
| 103 |
except Exception:
|
| 104 |
+
return []
|
| 105 |
+
|
| 106 |
|
| 107 |
async def get_detail(imdb_id: str, media_type: str) -> Optional[Dict[str, Any]]:
|
| 108 |
client = await _get_client()
|
|
|
|
| 148 |
except Exception:
|
| 149 |
return None
|
| 150 |
|
| 151 |
+
|
| 152 |
async def get_season(imdb_id: str, season_id: int, episode_id: int) -> Optional[Dict[str, Any]]:
|
| 153 |
client = await _get_client()
|
| 154 |
try:
|
Backend/helper/metadata.py
CHANGED
|
@@ -3,7 +3,10 @@ import traceback
|
|
| 3 |
import PTN
|
| 4 |
import re
|
| 5 |
from re import compile, IGNORECASE
|
| 6 |
-
from
|
|
|
|
|
|
|
|
|
|
| 7 |
from themoviedb import aioTMDb
|
| 8 |
from Backend.config import Telegram
|
| 9 |
import Backend
|
|
@@ -23,12 +26,19 @@ EPISODE_CACHE: dict = {}
|
|
| 23 |
# Concurrency semaphore for external API calls
|
| 24 |
API_SEMAPHORE = asyncio.Semaphore(12)
|
| 25 |
|
| 26 |
-
# -
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
def format_tmdb_image(path: str, size="w500") -> str:
|
| 28 |
if not path:
|
| 29 |
return ""
|
| 30 |
return f"https://image.tmdb.org/t/p/{size}{path}"
|
| 31 |
|
|
|
|
| 32 |
def get_tmdb_logo(images) -> str:
|
| 33 |
if not images:
|
| 34 |
return ""
|
|
@@ -45,7 +55,7 @@ def get_tmdb_logo(images) -> str:
|
|
| 45 |
if file_path:
|
| 46 |
return format_tmdb_image(file_path, "w300")
|
| 47 |
return ""
|
| 48 |
-
|
| 49 |
|
| 50 |
def format_imdb_images(imdb_id: str) -> dict:
|
| 51 |
if not imdb_id:
|
|
@@ -56,51 +66,291 @@ def format_imdb_images(imdb_id: str) -> dict:
|
|
| 56 |
"logo": f"https://images.metahub.space/logo/medium/{imdb_id}/img",
|
| 57 |
}
|
| 58 |
|
| 59 |
-
def extract_default_id(url: str) -> str | None:
|
| 60 |
-
# IMDb
|
| 61 |
-
imdb_match = re.search(r'/title/(tt\d+)', url)
|
| 62 |
-
if imdb_match:
|
| 63 |
-
return imdb_match.group(1)
|
| 64 |
|
| 65 |
-
|
| 66 |
-
tmdb_match = re.search(r'/((movie|tv))/(\d+)', url)
|
| 67 |
-
if tmdb_match:
|
| 68 |
-
return tmdb_match.group(3)
|
| 69 |
|
| 70 |
-
|
|
|
|
|
|
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
return imdb_id
|
| 82 |
-
except Exception as e:
|
| 83 |
-
LOGGER.warning(f"IMDb search failed for '{title}' [{type_}]: {e}")
|
| 84 |
return None
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
if
|
| 89 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
try:
|
| 91 |
async with API_SEMAPHORE:
|
| 92 |
if type_ == "movie":
|
| 93 |
-
results =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
else:
|
| 95 |
results = await tmdb.search().tv(query=title)
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
except Exception as e:
|
| 100 |
LOGGER.error(f"TMDb search failed for '{title}' [{type_}]: {e}")
|
| 101 |
-
TMDB_SEARCH_CACHE[
|
| 102 |
return None
|
| 103 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
async def _tmdb_movie_details(movie_id):
|
| 105 |
if movie_id in TMDB_DETAILS_CACHE:
|
| 106 |
return TMDB_DETAILS_CACHE[movie_id]
|
|
@@ -151,7 +401,11 @@ async def _tmdb_episode_details(tv_id, season, episode):
|
|
| 151 |
EPISODE_CACHE[key] = None
|
| 152 |
return None
|
| 153 |
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
async def metadata(filename: str, channel: int, msg_id, override_id: str = None) -> dict | None:
|
| 156 |
try:
|
| 157 |
parsed = PTN.parse(filename)
|
|
@@ -165,7 +419,6 @@ async def metadata(filename: str, channel: int, msg_id, override_id: str = None)
|
|
| 165 |
return None
|
| 166 |
|
| 167 |
# Skip split/multipart files
|
| 168 |
-
# if Telegram.SKIP_MULTIPART:
|
| 169 |
multipart_pattern = compile(r'(?:part|cd|disc|disk)[s._-]*\d+(?=\.\w+$)', IGNORECASE)
|
| 170 |
if multipart_pattern.search(filename):
|
| 171 |
LOGGER.info(f"Skipping {filename}: seems to be a split/multipart file")
|
|
@@ -176,6 +429,7 @@ async def metadata(filename: str, channel: int, msg_id, override_id: str = None)
|
|
| 176 |
episode = parsed.get("episode")
|
| 177 |
year = parsed.get("year")
|
| 178 |
quality = parsed.get("resolution")
|
|
|
|
| 179 |
if isinstance(season, list) or isinstance(episode, list):
|
| 180 |
LOGGER.warning(f"Invalid season/episode format for {filename}: {parsed}")
|
| 181 |
return None
|
|
@@ -189,20 +443,20 @@ async def metadata(filename: str, channel: int, msg_id, override_id: str = None)
|
|
| 189 |
LOGGER.info(f"No title parsed from: {filename} (parsed={parsed})")
|
| 190 |
return None
|
| 191 |
|
| 192 |
-
|
| 193 |
default_id = None
|
| 194 |
if override_id:
|
| 195 |
try:
|
| 196 |
default_id = extract_default_id(override_id) or override_id
|
| 197 |
except Exception:
|
| 198 |
pass
|
| 199 |
-
|
| 200 |
if not default_id:
|
| 201 |
try:
|
| 202 |
default_id = extract_default_id(Backend.USE_DEFAULT_ID)
|
| 203 |
except Exception:
|
| 204 |
pass
|
| 205 |
-
|
| 206 |
if not default_id:
|
| 207 |
try:
|
| 208 |
default_id = extract_default_id(filename)
|
|
@@ -217,16 +471,20 @@ async def metadata(filename: str, channel: int, msg_id, override_id: str = None)
|
|
| 217 |
|
| 218 |
try:
|
| 219 |
if season and episode:
|
| 220 |
-
LOGGER.info(f"Fetching TV metadata: {title} S{season}E{episode}")
|
| 221 |
return await fetch_tv_metadata(title, season, episode, encoded_string, year, quality, default_id)
|
| 222 |
else:
|
| 223 |
-
LOGGER.info(f"Fetching Movie metadata: {title} ({year})")
|
| 224 |
return await fetch_movie_metadata(title, encoded_string, year, quality, default_id)
|
| 225 |
except Exception as e:
|
| 226 |
LOGGER.error(f"Error while fetching metadata for {filename}: {e}\n{traceback.format_exc()}")
|
| 227 |
return None
|
| 228 |
|
| 229 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
|
| 231 |
imdb_id = None
|
| 232 |
tmdb_id = None
|
|
@@ -234,39 +492,36 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
|
|
| 234 |
imdb_ep = None
|
| 235 |
use_tmdb = False
|
| 236 |
|
| 237 |
-
# -------------------------------------------------------
|
| 238 |
-
# 1. Handle default ID
|
| 239 |
-
# -------------------------------------------------------
|
| 240 |
if default_id:
|
| 241 |
default_id = str(default_id)
|
| 242 |
if default_id.startswith("tt"):
|
| 243 |
imdb_id = default_id
|
| 244 |
-
use_tmdb = False
|
| 245 |
elif default_id.isdigit():
|
| 246 |
tmdb_id = int(default_id)
|
| 247 |
use_tmdb = True
|
| 248 |
|
| 249 |
-
# -------------------------------------------------------
|
| 250 |
-
# 2.
|
| 251 |
-
# -------------------------------------------------------
|
| 252 |
if not imdb_id and not tmdb_id:
|
| 253 |
-
imdb_id = await safe_imdb_search(title, "tvSeries")
|
| 254 |
use_tmdb = not bool(imdb_id)
|
| 255 |
|
| 256 |
-
# -------------------------------------------------------
|
| 257 |
-
# 3. IMDb
|
| 258 |
-
# -------------------------------------------------------
|
| 259 |
if imdb_id and not use_tmdb:
|
| 260 |
try:
|
| 261 |
-
|
| 262 |
-
if imdb_id in IMDB_CACHE:
|
| 263 |
imdb_tv = IMDB_CACHE[imdb_id]
|
| 264 |
else:
|
| 265 |
async with API_SEMAPHORE:
|
| 266 |
imdb_tv = await get_detail(imdb_id=imdb_id, media_type="tvSeries")
|
| 267 |
IMDB_CACHE[imdb_id] = imdb_tv
|
| 268 |
|
| 269 |
-
# ----- episode details
|
| 270 |
ep_key = f"{imdb_id}::{season}::{episode}"
|
| 271 |
if ep_key in EPISODE_CACHE:
|
| 272 |
imdb_ep = EPISODE_CACHE[ep_key]
|
|
@@ -281,39 +536,50 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
|
|
| 281 |
imdb_ep = None
|
| 282 |
use_tmdb = True
|
| 283 |
|
| 284 |
-
# -------------------------------------------------------
|
| 285 |
-
# 4.
|
| 286 |
-
# -
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
-
# =======================================================
|
| 294 |
-
# 5. TMDb MODE
|
| 295 |
-
# =======================================================
|
| 296 |
if must_use_tmdb:
|
| 297 |
-
LOGGER.info(f"No valid
|
| 298 |
|
| 299 |
-
# Search TMDb by title
|
| 300 |
if not tmdb_id:
|
|
|
|
| 301 |
tmdb_search = await safe_tmdb_search(title, "tv", year)
|
|
|
|
|
|
|
|
|
|
| 302 |
if not tmdb_search:
|
| 303 |
-
LOGGER.
|
|
|
|
|
|
|
|
|
|
| 304 |
return None
|
| 305 |
tmdb_id = tmdb_search.id
|
| 306 |
|
| 307 |
-
# Fetch full TV show details
|
| 308 |
tv = await _tmdb_tv_details(tmdb_id)
|
| 309 |
if not tv:
|
| 310 |
-
LOGGER.
|
| 311 |
return None
|
| 312 |
|
| 313 |
-
# Fetch episode
|
| 314 |
ep = await _tmdb_episode_details(tmdb_id, season, episode)
|
| 315 |
|
| 316 |
-
# Cast list
|
| 317 |
credits = getattr(tv, "credits", None) or {}
|
| 318 |
cast_arr = getattr(credits, "cast", []) or []
|
| 319 |
cast = [
|
|
@@ -321,11 +587,8 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
|
|
| 321 |
for c in cast_arr
|
| 322 |
]
|
| 323 |
|
| 324 |
-
# Runtime (prefer episode → series → empty)
|
| 325 |
ep_runtime = getattr(ep, "runtime", None) if ep else None
|
| 326 |
-
series_runtime = (
|
| 327 |
-
tv.episode_run_time[0] if getattr(tv, "episode_run_time", None) else None
|
| 328 |
-
)
|
| 329 |
runtime_val = ep_runtime or series_runtime
|
| 330 |
runtime = f"{runtime_val} min" if runtime_val else ""
|
| 331 |
|
|
@@ -343,10 +606,9 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
|
|
| 343 |
"media_type": "tv",
|
| 344 |
"cast": cast,
|
| 345 |
"runtime": str(runtime),
|
| 346 |
-
|
| 347 |
"season_number": season,
|
| 348 |
"episode_number": episode,
|
| 349 |
-
"episode_title": getattr(ep, "name", f"S{season}E{episode}") if ep else f"S{season}E{episode}",
|
| 350 |
"episode_backdrop": format_tmdb_image(getattr(ep, "still_path", None), "original") if ep else "",
|
| 351 |
"episode_overview": getattr(ep, "overview", "") if ep else "",
|
| 352 |
"episode_released": (
|
|
@@ -354,21 +616,19 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
|
|
| 354 |
if getattr(ep, "air_date", None)
|
| 355 |
else ""
|
| 356 |
),
|
| 357 |
-
|
| 358 |
"quality": quality,
|
| 359 |
"encoded_string": encoded_string,
|
| 360 |
}
|
| 361 |
|
| 362 |
-
#
|
| 363 |
-
#
|
| 364 |
-
#
|
| 365 |
imdb = imdb_tv or {}
|
| 366 |
ep = imdb_ep or {}
|
| 367 |
-
|
| 368 |
images = format_imdb_images(imdb_id)
|
| 369 |
|
| 370 |
return {
|
| 371 |
-
"tmdb_id": imdb.get("moviedb_id") or imdb_id.replace("tt", ""),
|
| 372 |
"imdb_id": imdb_id,
|
| 373 |
"title": imdb.get("title", title),
|
| 374 |
"year": imdb.get("releaseDetailed", {}).get("year", 0),
|
|
@@ -378,66 +638,58 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
|
|
| 378 |
"backdrop": images["backdrop"],
|
| 379 |
"logo": images["logo"],
|
| 380 |
"cast": imdb.get("cast", []),
|
| 381 |
-
"runtime": str(imdb.get("runtime") or ""),
|
| 382 |
"genres": imdb.get("genre", []),
|
| 383 |
"media_type": "tv",
|
| 384 |
-
|
| 385 |
"season_number": season,
|
| 386 |
"episode_number": episode,
|
| 387 |
-
"episode_title": ep.get("title", f"S{season}E{episode}"),
|
| 388 |
"episode_backdrop": ep.get("image", ""),
|
| 389 |
"episode_overview": ep.get("plot", ""),
|
| 390 |
"episode_released": str(ep.get("released", "")),
|
| 391 |
-
|
| 392 |
"quality": quality,
|
| 393 |
"encoded_string": encoded_string,
|
| 394 |
}
|
| 395 |
|
| 396 |
|
| 397 |
-
#
|
|
|
|
|
|
|
|
|
|
| 398 |
async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
|
| 399 |
imdb_id = None
|
| 400 |
tmdb_id = None
|
| 401 |
imdb_details = None
|
| 402 |
use_tmdb = False
|
| 403 |
|
| 404 |
-
# -------------------------------------------------------
|
| 405 |
-
# 1.
|
| 406 |
-
# -------------------------------------------------------
|
| 407 |
if default_id:
|
| 408 |
default_id = str(default_id).strip()
|
| 409 |
-
|
| 410 |
if default_id.startswith("tt"):
|
| 411 |
imdb_id = default_id
|
| 412 |
-
use_tmdb = False
|
| 413 |
elif default_id.isdigit():
|
| 414 |
tmdb_id = int(default_id)
|
| 415 |
-
use_tmdb = True
|
| 416 |
|
| 417 |
-
# -------------------------------------------------------
|
| 418 |
-
# 2.
|
| 419 |
-
# -------------------------------------------------------
|
| 420 |
if not imdb_id and not tmdb_id:
|
| 421 |
-
imdb_id = await safe_imdb_search(
|
| 422 |
-
f"{title} {year}" if year else title,
|
| 423 |
-
"movie"
|
| 424 |
-
)
|
| 425 |
use_tmdb = not bool(imdb_id)
|
| 426 |
|
| 427 |
-
# -------------------------------------------------------
|
| 428 |
-
# 3.
|
| 429 |
-
# -------------------------------------------------------
|
| 430 |
if imdb_id and not use_tmdb:
|
| 431 |
try:
|
| 432 |
-
if imdb_id in IMDB_CACHE:
|
| 433 |
imdb_details = IMDB_CACHE[imdb_id]
|
| 434 |
else:
|
| 435 |
async with API_SEMAPHORE:
|
| 436 |
-
imdb_details = await get_detail(
|
| 437 |
-
imdb_id=imdb_id,
|
| 438 |
-
media_type="movie"
|
| 439 |
-
)
|
| 440 |
-
|
| 441 |
IMDB_CACHE[imdb_id] = imdb_details
|
| 442 |
|
| 443 |
except Exception as e:
|
|
@@ -445,36 +697,47 @@ async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, d
|
|
| 445 |
imdb_details = None
|
| 446 |
use_tmdb = True
|
| 447 |
|
| 448 |
-
# -------------------------------------------------------
|
| 449 |
-
# 4.
|
| 450 |
-
# -------------------------------------------------------
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 456 |
|
| 457 |
-
# =======================================================
|
| 458 |
-
# 5. TMDb MODE
|
| 459 |
-
# =======================================================
|
| 460 |
if must_use_tmdb:
|
| 461 |
-
LOGGER.info(f"No valid
|
| 462 |
|
| 463 |
-
# TMDb search if id unknown
|
| 464 |
if not tmdb_id:
|
| 465 |
tmdb_result = await safe_tmdb_search(title, "movie", year)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 466 |
if not tmdb_result:
|
| 467 |
-
LOGGER.
|
|
|
|
|
|
|
|
|
|
| 468 |
return None
|
| 469 |
tmdb_id = tmdb_result.id
|
| 470 |
|
| 471 |
-
# Fetch TMDb details
|
| 472 |
movie = await _tmdb_movie_details(tmdb_id)
|
| 473 |
if not movie:
|
| 474 |
-
LOGGER.
|
| 475 |
return None
|
| 476 |
|
| 477 |
-
# Cast extraction
|
| 478 |
credits = getattr(movie, "credits", None) or {}
|
| 479 |
cast_arr = getattr(credits, "cast", []) or []
|
| 480 |
cast_names = [
|
|
@@ -503,14 +766,14 @@ async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, d
|
|
| 503 |
"encoded_string": encoded_string,
|
| 504 |
}
|
| 505 |
|
| 506 |
-
#
|
| 507 |
-
#
|
| 508 |
-
#
|
| 509 |
images = format_imdb_images(imdb_id)
|
| 510 |
imdb = imdb_details or {}
|
| 511 |
|
| 512 |
return {
|
| 513 |
-
"tmdb_id": imdb.get("moviedb_id") or imdb_id.replace("tt", ""),
|
| 514 |
"imdb_id": imdb_id,
|
| 515 |
"title": imdb.get("title", title),
|
| 516 |
"year": imdb.get("releaseDetailed", {}).get("year", 0),
|
|
@@ -528,6 +791,10 @@ async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, d
|
|
| 528 |
}
|
| 529 |
|
| 530 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 531 |
async def search_movie_candidates(query: str, year: int | None = None, limit: int = 8) -> list[dict]:
|
| 532 |
query = (query or "").strip()
|
| 533 |
if not query:
|
|
@@ -536,7 +803,6 @@ async def search_movie_candidates(query: str, year: int | None = None, limit: in
|
|
| 536 |
results: list[dict] = []
|
| 537 |
seen: set[tuple[str, str]] = set()
|
| 538 |
|
| 539 |
-
# IMDb/Cinemeta top result
|
| 540 |
try:
|
| 541 |
imdb_result = await search_title(query=query, type="movie")
|
| 542 |
if imdb_result and imdb_result.get("id"):
|
|
@@ -556,10 +822,13 @@ async def search_movie_candidates(query: str, year: int | None = None, limit: in
|
|
| 556 |
except Exception as e:
|
| 557 |
LOGGER.warning(f"IMDb movie candidate search failed for '{query}': {e}")
|
| 558 |
|
| 559 |
-
# TMDb multiple results
|
| 560 |
try:
|
| 561 |
async with API_SEMAPHORE:
|
| 562 |
-
tmdb_results =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 563 |
|
| 564 |
for item in (tmdb_results or [])[:limit]:
|
| 565 |
tmdb_id = getattr(item, "id", None)
|
|
@@ -606,7 +875,6 @@ async def search_tv_candidates(query: str, limit: int = 8) -> list[dict]:
|
|
| 606 |
results: list[dict] = []
|
| 607 |
seen: set[tuple[str, str]] = set()
|
| 608 |
|
| 609 |
-
# IMDb/Cinemeta top result
|
| 610 |
try:
|
| 611 |
imdb_result = await search_title(query=query, type="tvSeries")
|
| 612 |
if imdb_result and imdb_result.get("id"):
|
|
@@ -626,7 +894,6 @@ async def search_tv_candidates(query: str, limit: int = 8) -> list[dict]:
|
|
| 626 |
except Exception as e:
|
| 627 |
LOGGER.warning(f"IMDb TV candidate search failed for '{query}': {e}")
|
| 628 |
|
| 629 |
-
# TMDb multiple results
|
| 630 |
try:
|
| 631 |
async with API_SEMAPHORE:
|
| 632 |
tmdb_results = await tmdb.search().tv(query=query)
|
|
@@ -668,6 +935,10 @@ async def search_tv_candidates(query: str, limit: int = 8) -> list[dict]:
|
|
| 668 |
return results[:limit]
|
| 669 |
|
| 670 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 671 |
async def fetch_selected_movie_metadata(selected_id: str) -> dict | None:
|
| 672 |
selected_id = str(selected_id).strip()
|
| 673 |
if not selected_id:
|
|
|
|
| 3 |
import PTN
|
| 4 |
import re
|
| 5 |
from re import compile, IGNORECASE
|
| 6 |
+
from difflib import SequenceMatcher
|
| 7 |
+
from typing import Optional, List
|
| 8 |
+
|
| 9 |
+
from Backend.helper.imdb import get_detail, get_season, search_title, search_title_multi
|
| 10 |
from themoviedb import aioTMDb
|
| 11 |
from Backend.config import Telegram
|
| 12 |
import Backend
|
|
|
|
| 26 |
# Concurrency semaphore for external API calls
|
| 27 |
API_SEMAPHORE = asyncio.Semaphore(12)
|
| 28 |
|
| 29 |
+
# Minimum title-similarity score to accept a Cinemeta result
|
| 30 |
+
_CINEMETA_THRESHOLD = 0.60
|
| 31 |
+
# Minimum score to accept TMDb first-result (without year bonus it's stricter)
|
| 32 |
+
_TMDB_THRESHOLD = 0.55
|
| 33 |
+
|
| 34 |
+
# ----------------- Image helpers -----------------
|
| 35 |
+
|
| 36 |
def format_tmdb_image(path: str, size="w500") -> str:
|
| 37 |
if not path:
|
| 38 |
return ""
|
| 39 |
return f"https://image.tmdb.org/t/p/{size}{path}"
|
| 40 |
|
| 41 |
+
|
| 42 |
def get_tmdb_logo(images) -> str:
|
| 43 |
if not images:
|
| 44 |
return ""
|
|
|
|
| 55 |
if file_path:
|
| 56 |
return format_tmdb_image(file_path, "w300")
|
| 57 |
return ""
|
| 58 |
+
|
| 59 |
|
| 60 |
def format_imdb_images(imdb_id: str) -> dict:
|
| 61 |
if not imdb_id:
|
|
|
|
| 66 |
"logo": f"https://images.metahub.space/logo/medium/{imdb_id}/img",
|
| 67 |
}
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
+
# ----------------- ID extraction -----------------
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
+
def extract_default_id(text: str) -> str | None:
|
| 73 |
+
"""
|
| 74 |
+
Extract an IMDb (tt…) or TMDb (numeric) ID from arbitrary text.
|
| 75 |
|
| 76 |
+
Handles:
|
| 77 |
+
• Bare IMDb IDs: tt1234567
|
| 78 |
+
• IMDb URLs: https://www.imdb.com/title/tt1234567/
|
| 79 |
+
• TMDb movie URLs: https://www.themoviedb.org/movie/12345
|
| 80 |
+
• TMDb TV URLs: https://www.themoviedb.org/tv/12345
|
| 81 |
+
• Bare TMDb IDs are intentionally NOT extracted from plain numbers to
|
| 82 |
+
avoid false matches; they must come via a URL or an explicit override.
|
| 83 |
+
"""
|
| 84 |
+
if not text:
|
|
|
|
|
|
|
|
|
|
| 85 |
return None
|
| 86 |
|
| 87 |
+
# 1. Bare IMDb ID (tt followed by 7–10 digits, word-bounded)
|
| 88 |
+
bare_imdb = re.search(r'\b(tt\d{7,10})\b', text)
|
| 89 |
+
if bare_imdb:
|
| 90 |
+
return bare_imdb.group(1)
|
| 91 |
+
|
| 92 |
+
# 2. IMDb URL
|
| 93 |
+
imdb_url = re.search(r'/title/(tt\d+)', text)
|
| 94 |
+
if imdb_url:
|
| 95 |
+
return imdb_url.group(1)
|
| 96 |
+
|
| 97 |
+
# 3. TMDb URL (/movie/NNN or /tv/NNN)
|
| 98 |
+
tmdb_url = re.search(r'/(?:movie|tv)/(\d+)', text)
|
| 99 |
+
if tmdb_url:
|
| 100 |
+
return tmdb_url.group(1)
|
| 101 |
+
|
| 102 |
+
return None
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# ----------------- Fuzzy-matching helpers -----------------
|
| 106 |
+
|
| 107 |
+
def _normalize_title(title: str) -> str:
|
| 108 |
+
"""Lower-case, strip leading articles, collapse punctuation to spaces."""
|
| 109 |
+
if not title:
|
| 110 |
+
return ""
|
| 111 |
+
t = title.lower().strip()
|
| 112 |
+
# Remove leading articles
|
| 113 |
+
t = re.sub(r'^\b(the|a|an)\b\s+', '', t)
|
| 114 |
+
# Replace punctuation with spaces
|
| 115 |
+
t = re.sub(r'[^\w\s]', ' ', t)
|
| 116 |
+
t = re.sub(r'\s+', ' ', t).strip()
|
| 117 |
+
return t
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _title_similarity(t1: str, t2: str) -> float:
|
| 121 |
+
"""Fuzzy similarity between two titles, 0–1."""
|
| 122 |
+
n1, n2 = _normalize_title(t1), _normalize_title(t2)
|
| 123 |
+
if not n1 or not n2:
|
| 124 |
+
return 0.0
|
| 125 |
+
return SequenceMatcher(None, n1, n2).ratio()
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _year_from_str(year_val) -> int:
|
| 129 |
+
"""Extract the first 4-digit year from strings like '2023', '2020–', '2019-2022'."""
|
| 130 |
+
if not year_val:
|
| 131 |
+
return 0
|
| 132 |
+
m = re.search(r'(\d{4})', str(year_val))
|
| 133 |
+
return int(m.group(1)) if m else 0
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _score_candidate(
|
| 137 |
+
query_title: str,
|
| 138 |
+
query_year: Optional[int],
|
| 139 |
+
result_title: str,
|
| 140 |
+
result_year: int,
|
| 141 |
+
) -> float:
|
| 142 |
+
"""
|
| 143 |
+
Combined score for a single API candidate.
|
| 144 |
+
Base = title similarity; year match adds a bonus.
|
| 145 |
+
"""
|
| 146 |
+
score = _title_similarity(query_title, result_title)
|
| 147 |
+
|
| 148 |
+
if query_year and result_year:
|
| 149 |
+
diff = abs(int(query_year) - result_year)
|
| 150 |
+
if diff == 0:
|
| 151 |
+
score = min(1.0, score + 0.20) # exact year: strong boost
|
| 152 |
+
elif diff == 1:
|
| 153 |
+
score = min(1.0, score + 0.07) # off by one: small boost
|
| 154 |
+
elif diff <= 2:
|
| 155 |
+
pass # neutral
|
| 156 |
+
else:
|
| 157 |
+
score = max(0.0, score - 0.10 * (diff - 2)) # growing penalty
|
| 158 |
+
|
| 159 |
+
return score
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _build_query_variants(title: str, year: Optional[int] = None) -> List[str]:
|
| 163 |
+
"""
|
| 164 |
+
Build an ordered list of search query variants to try when the primary
|
| 165 |
+
query produces a poor match.
|
| 166 |
+
|
| 167 |
+
Order: most-specific → least-specific.
|
| 168 |
+
"""
|
| 169 |
+
variants: List[str] = []
|
| 170 |
+
|
| 171 |
+
# 1. Original title (as parsed by PTN)
|
| 172 |
+
variants.append(title)
|
| 173 |
+
|
| 174 |
+
# 2. Title with year appended (often improves Cinemeta recall for movies)
|
| 175 |
+
if year:
|
| 176 |
+
variants.append(f"{title} {year}")
|
| 177 |
+
|
| 178 |
+
# 3. Punctuation-stripped version (handles colons, hyphens, apostrophes)
|
| 179 |
+
stripped = re.sub(r'[^\w\s]', ' ', title)
|
| 180 |
+
stripped = re.sub(r'\s+', ' ', stripped).strip()
|
| 181 |
+
if stripped and stripped.lower() != title.lower():
|
| 182 |
+
variants.append(stripped)
|
| 183 |
+
if year:
|
| 184 |
+
variants.append(f"{stripped} {year}")
|
| 185 |
+
|
| 186 |
+
# 4. Without leading article (The / A / An)
|
| 187 |
+
no_article = re.sub(r'^\b(the|a|an)\b\s+', '', title, flags=IGNORECASE).strip()
|
| 188 |
+
if no_article and no_article.lower() != title.lower():
|
| 189 |
+
variants.append(no_article)
|
| 190 |
+
|
| 191 |
+
# Deduplicate, preserve order, drop empty strings
|
| 192 |
+
seen: set = set()
|
| 193 |
+
result: List[str] = []
|
| 194 |
+
for v in variants:
|
| 195 |
+
k = v.lower()
|
| 196 |
+
if k not in seen and v:
|
| 197 |
+
seen.add(k)
|
| 198 |
+
result.append(v)
|
| 199 |
+
return result
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ----------------- Cached API wrappers -----------------
|
| 203 |
+
|
| 204 |
+
async def safe_imdb_search(title: str, type_: str, year: Optional[int] = None) -> str | None:
|
| 205 |
+
"""
|
| 206 |
+
Search Cinemeta for *title* (+ optional *year*) with:
|
| 207 |
+
• Multiple query variants (original, stripped, with-year, no-article)
|
| 208 |
+
• Fuzzy title + year scoring across all returned results
|
| 209 |
+
• Acceptance threshold so partial/wrong matches are rejected early
|
| 210 |
+
• INFO log explaining what happened when no confident match is found
|
| 211 |
+
"""
|
| 212 |
+
cache_key = f"imdb::{type_}::{title}::{year}"
|
| 213 |
+
if cache_key in IMDB_CACHE:
|
| 214 |
+
return IMDB_CACHE[cache_key]
|
| 215 |
+
|
| 216 |
+
query_variants = _build_query_variants(title, year)
|
| 217 |
+
|
| 218 |
+
best_id: str | None = None
|
| 219 |
+
best_score: float = 0.0
|
| 220 |
+
best_result_title: str = ""
|
| 221 |
+
|
| 222 |
+
for query in query_variants:
|
| 223 |
+
try:
|
| 224 |
+
async with API_SEMAPHORE:
|
| 225 |
+
results = await search_title_multi(query=query, type=type_, limit=8)
|
| 226 |
+
|
| 227 |
+
for r in results:
|
| 228 |
+
r_title = r.get("title", "")
|
| 229 |
+
r_year = _year_from_str(r.get("year", ""))
|
| 230 |
+
score = _score_candidate(title, year, r_title, r_year)
|
| 231 |
+
|
| 232 |
+
if score > best_score:
|
| 233 |
+
best_score = score
|
| 234 |
+
best_id = r.get("id")
|
| 235 |
+
best_result_title = r_title
|
| 236 |
+
|
| 237 |
+
# Early-exit: perfect / near-perfect match
|
| 238 |
+
if best_score >= 0.92:
|
| 239 |
+
break
|
| 240 |
+
|
| 241 |
+
except Exception as e:
|
| 242 |
+
LOGGER.warning(f"Cinemeta search variant '{query}' [{type_}] failed: {e}")
|
| 243 |
+
|
| 244 |
+
# Early-exit across variants too
|
| 245 |
+
if best_score >= 0.92:
|
| 246 |
+
break
|
| 247 |
+
|
| 248 |
+
if best_score >= _CINEMETA_THRESHOLD and best_id:
|
| 249 |
+
LOGGER.info(
|
| 250 |
+
f"Cinemeta match: '{title}' (year={year}) → "
|
| 251 |
+
f"'{best_result_title}' [{best_id}] (score={best_score:.2f})"
|
| 252 |
+
)
|
| 253 |
+
IMDB_CACHE[cache_key] = best_id
|
| 254 |
+
return best_id
|
| 255 |
+
|
| 256 |
+
# Log a clear, actionable INFO message so operators know why it fell back
|
| 257 |
+
if best_id:
|
| 258 |
+
LOGGER.info(
|
| 259 |
+
f"Cinemeta low-confidence for '{title}' (year={year}, type={type_}) "
|
| 260 |
+
f"| best candidate: '{best_result_title}' [{best_id}] score={best_score:.2f} "
|
| 261 |
+
f"(threshold={_CINEMETA_THRESHOLD}) → falling back to TMDb"
|
| 262 |
+
)
|
| 263 |
+
else:
|
| 264 |
+
LOGGER.info(
|
| 265 |
+
f"Cinemeta returned no results for '{title}' (year={year}, type={type_}) "
|
| 266 |
+
f"| tried variants: {query_variants} → falling back to TMDb"
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
IMDB_CACHE[cache_key] = None
|
| 270 |
+
return None
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
async def safe_tmdb_search(title: str, type_: str, year: Optional[int] = None):
|
| 274 |
+
"""
|
| 275 |
+
Search TMDb for *title*, scoring all returned results by title similarity
|
| 276 |
+
and year proximity. Falls back to a year-agnostic retry when the
|
| 277 |
+
year-constrained search yields nothing.
|
| 278 |
+
"""
|
| 279 |
+
cache_key = f"tmdb_search::{type_}::{title}::{year}"
|
| 280 |
+
if cache_key in TMDB_SEARCH_CACHE:
|
| 281 |
+
return TMDB_SEARCH_CACHE[cache_key]
|
| 282 |
+
|
| 283 |
try:
|
| 284 |
async with API_SEMAPHORE:
|
| 285 |
if type_ == "movie":
|
| 286 |
+
results = (
|
| 287 |
+
await tmdb.search().movies(query=title, year=year)
|
| 288 |
+
if year
|
| 289 |
+
else await tmdb.search().movies(query=title)
|
| 290 |
+
)
|
| 291 |
+
# Year-constrained search sometimes returns nothing for new/limited releases
|
| 292 |
+
if not results and year:
|
| 293 |
+
async with API_SEMAPHORE:
|
| 294 |
+
results = await tmdb.search().movies(query=title)
|
| 295 |
else:
|
| 296 |
results = await tmdb.search().tv(query=title)
|
| 297 |
+
|
| 298 |
+
best = _pick_best_tmdb_result(results, title, year, type_)
|
| 299 |
+
|
| 300 |
+
if best is None and results:
|
| 301 |
+
# Log what the top result actually was so operators can diagnose
|
| 302 |
+
top = results[0]
|
| 303 |
+
top_title = getattr(top, "title" if type_ == "movie" else "name", "?")
|
| 304 |
+
LOGGER.info(
|
| 305 |
+
f"TMDb '{title}' (year={year}) top result '{top_title}' "
|
| 306 |
+
f"did not meet threshold – no confident match"
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
TMDB_SEARCH_CACHE[cache_key] = best
|
| 310 |
+
return best
|
| 311 |
+
|
| 312 |
except Exception as e:
|
| 313 |
LOGGER.error(f"TMDb search failed for '{title}' [{type_}]: {e}")
|
| 314 |
+
TMDB_SEARCH_CACHE[cache_key] = None
|
| 315 |
return None
|
| 316 |
|
| 317 |
+
|
| 318 |
+
def _pick_best_tmdb_result(results, query_title: str, query_year: Optional[int], type_: str):
|
| 319 |
+
"""
|
| 320 |
+
Score TMDb search results and return the best one above threshold,
|
| 321 |
+
or None if nothing is confident enough.
|
| 322 |
+
"""
|
| 323 |
+
if not results:
|
| 324 |
+
return None
|
| 325 |
+
|
| 326 |
+
best_item = None
|
| 327 |
+
best_score = 0.0
|
| 328 |
+
|
| 329 |
+
for item in results:
|
| 330 |
+
if type_ == "movie":
|
| 331 |
+
r_title = getattr(item, "title", "") or ""
|
| 332 |
+
release = getattr(item, "release_date", None)
|
| 333 |
+
r_year = getattr(release, "year", 0) if release else 0
|
| 334 |
+
else:
|
| 335 |
+
r_title = getattr(item, "name", "") or ""
|
| 336 |
+
first_air = getattr(item, "first_air_date", None)
|
| 337 |
+
r_year = getattr(first_air, "year", 0) if first_air else 0
|
| 338 |
+
|
| 339 |
+
score = _score_candidate(query_title, query_year, r_title, r_year)
|
| 340 |
+
|
| 341 |
+
if score > best_score:
|
| 342 |
+
best_score = score
|
| 343 |
+
best_item = item
|
| 344 |
+
|
| 345 |
+
if best_score >= 0.92:
|
| 346 |
+
break
|
| 347 |
+
|
| 348 |
+
if best_score >= _TMDB_THRESHOLD and best_item is not None:
|
| 349 |
+
return best_item
|
| 350 |
+
|
| 351 |
+
return None
|
| 352 |
+
|
| 353 |
+
|
| 354 |
async def _tmdb_movie_details(movie_id):
|
| 355 |
if movie_id in TMDB_DETAILS_CACHE:
|
| 356 |
return TMDB_DETAILS_CACHE[movie_id]
|
|
|
|
| 401 |
EPISODE_CACHE[key] = None
|
| 402 |
return None
|
| 403 |
|
| 404 |
+
|
| 405 |
+
# =============================================================================
|
| 406 |
+
# Main entry-point
|
| 407 |
+
# =============================================================================
|
| 408 |
+
|
| 409 |
async def metadata(filename: str, channel: int, msg_id, override_id: str = None) -> dict | None:
|
| 410 |
try:
|
| 411 |
parsed = PTN.parse(filename)
|
|
|
|
| 419 |
return None
|
| 420 |
|
| 421 |
# Skip split/multipart files
|
|
|
|
| 422 |
multipart_pattern = compile(r'(?:part|cd|disc|disk)[s._-]*\d+(?=\.\w+$)', IGNORECASE)
|
| 423 |
if multipart_pattern.search(filename):
|
| 424 |
LOGGER.info(f"Skipping {filename}: seems to be a split/multipart file")
|
|
|
|
| 429 |
episode = parsed.get("episode")
|
| 430 |
year = parsed.get("year")
|
| 431 |
quality = parsed.get("resolution")
|
| 432 |
+
|
| 433 |
if isinstance(season, list) or isinstance(episode, list):
|
| 434 |
LOGGER.warning(f"Invalid season/episode format for {filename}: {parsed}")
|
| 435 |
return None
|
|
|
|
| 443 |
LOGGER.info(f"No title parsed from: {filename} (parsed={parsed})")
|
| 444 |
return None
|
| 445 |
|
| 446 |
+
# --- Resolve override / default ID ---
|
| 447 |
default_id = None
|
| 448 |
if override_id:
|
| 449 |
try:
|
| 450 |
default_id = extract_default_id(override_id) or override_id
|
| 451 |
except Exception:
|
| 452 |
pass
|
| 453 |
+
|
| 454 |
if not default_id:
|
| 455 |
try:
|
| 456 |
default_id = extract_default_id(Backend.USE_DEFAULT_ID)
|
| 457 |
except Exception:
|
| 458 |
pass
|
| 459 |
+
|
| 460 |
if not default_id:
|
| 461 |
try:
|
| 462 |
default_id = extract_default_id(filename)
|
|
|
|
| 471 |
|
| 472 |
try:
|
| 473 |
if season and episode:
|
| 474 |
+
LOGGER.info(f"Fetching TV metadata: {title} S{season:02d}E{episode:02d} (year={year})")
|
| 475 |
return await fetch_tv_metadata(title, season, episode, encoded_string, year, quality, default_id)
|
| 476 |
else:
|
| 477 |
+
LOGGER.info(f"Fetching Movie metadata: {title} (year={year})")
|
| 478 |
return await fetch_movie_metadata(title, encoded_string, year, quality, default_id)
|
| 479 |
except Exception as e:
|
| 480 |
LOGGER.error(f"Error while fetching metadata for {filename}: {e}\n{traceback.format_exc()}")
|
| 481 |
return None
|
| 482 |
|
| 483 |
+
|
| 484 |
+
# =============================================================================
|
| 485 |
+
# TV metadata
|
| 486 |
+
# =============================================================================
|
| 487 |
+
|
| 488 |
async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
|
| 489 |
imdb_id = None
|
| 490 |
tmdb_id = None
|
|
|
|
| 492 |
imdb_ep = None
|
| 493 |
use_tmdb = False
|
| 494 |
|
| 495 |
+
# ------------------------------------------------------------------
|
| 496 |
+
# 1. Handle explicit default ID
|
| 497 |
+
# ------------------------------------------------------------------
|
| 498 |
if default_id:
|
| 499 |
default_id = str(default_id)
|
| 500 |
if default_id.startswith("tt"):
|
| 501 |
imdb_id = default_id
|
|
|
|
| 502 |
elif default_id.isdigit():
|
| 503 |
tmdb_id = int(default_id)
|
| 504 |
use_tmdb = True
|
| 505 |
|
| 506 |
+
# ------------------------------------------------------------------
|
| 507 |
+
# 2. No ID → fuzzy Cinemeta search with query variants
|
| 508 |
+
# ------------------------------------------------------------------
|
| 509 |
if not imdb_id and not tmdb_id:
|
| 510 |
+
imdb_id = await safe_imdb_search(title, "tvSeries", year)
|
| 511 |
use_tmdb = not bool(imdb_id)
|
| 512 |
|
| 513 |
+
# ------------------------------------------------------------------
|
| 514 |
+
# 3. IMDb / Cinemeta detail fetch
|
| 515 |
+
# ------------------------------------------------------------------
|
| 516 |
if imdb_id and not use_tmdb:
|
| 517 |
try:
|
| 518 |
+
if imdb_id in IMDB_CACHE and isinstance(IMDB_CACHE.get(imdb_id), dict):
|
|
|
|
| 519 |
imdb_tv = IMDB_CACHE[imdb_id]
|
| 520 |
else:
|
| 521 |
async with API_SEMAPHORE:
|
| 522 |
imdb_tv = await get_detail(imdb_id=imdb_id, media_type="tvSeries")
|
| 523 |
IMDB_CACHE[imdb_id] = imdb_tv
|
| 524 |
|
|
|
|
| 525 |
ep_key = f"{imdb_id}::{season}::{episode}"
|
| 526 |
if ep_key in EPISODE_CACHE:
|
| 527 |
imdb_ep = EPISODE_CACHE[ep_key]
|
|
|
|
| 536 |
imdb_ep = None
|
| 537 |
use_tmdb = True
|
| 538 |
|
| 539 |
+
# ------------------------------------------------------------------
|
| 540 |
+
# 4. Validate IMDb result against query title (guard against Cinemeta
|
| 541 |
+
# returning a stale wrong hit despite the fuzzy pre-filter)
|
| 542 |
+
# ------------------------------------------------------------------
|
| 543 |
+
if imdb_tv and not use_tmdb:
|
| 544 |
+
matched_title = imdb_tv.get("title", "")
|
| 545 |
+
sim = _title_similarity(title, matched_title)
|
| 546 |
+
if sim < _CINEMETA_THRESHOLD:
|
| 547 |
+
LOGGER.info(
|
| 548 |
+
f"IMDb detail title mismatch for '{title}': "
|
| 549 |
+
f"got '{matched_title}' (sim={sim:.2f}) → switching to TMDb"
|
| 550 |
+
)
|
| 551 |
+
imdb_tv = None
|
| 552 |
+
use_tmdb = True
|
| 553 |
+
|
| 554 |
+
# ------------------------------------------------------------------
|
| 555 |
+
# 5. Fallback: TMDb
|
| 556 |
+
# ------------------------------------------------------------------
|
| 557 |
+
must_use_tmdb = use_tmdb or not imdb_tv
|
| 558 |
|
|
|
|
|
|
|
|
|
|
| 559 |
if must_use_tmdb:
|
| 560 |
+
LOGGER.info(f"No valid Cinemeta TV data for '{title}' S{season:02d}E{episode:02d} → using TMDb")
|
| 561 |
|
|
|
|
| 562 |
if not tmdb_id:
|
| 563 |
+
# Try with year first, then without
|
| 564 |
tmdb_search = await safe_tmdb_search(title, "tv", year)
|
| 565 |
+
if not tmdb_search and year:
|
| 566 |
+
tmdb_search = await safe_tmdb_search(title, "tv", None)
|
| 567 |
+
|
| 568 |
if not tmdb_search:
|
| 569 |
+
LOGGER.info(
|
| 570 |
+
f"No TMDb TV result for '{title}' S{season:02d}E{episode:02d} "
|
| 571 |
+
f"(year={year}) – metadata unavailable"
|
| 572 |
+
)
|
| 573 |
return None
|
| 574 |
tmdb_id = tmdb_search.id
|
| 575 |
|
|
|
|
| 576 |
tv = await _tmdb_tv_details(tmdb_id)
|
| 577 |
if not tv:
|
| 578 |
+
LOGGER.info(f"TMDb TV details failed for id={tmdb_id} ('{title}')")
|
| 579 |
return None
|
| 580 |
|
|
|
|
| 581 |
ep = await _tmdb_episode_details(tmdb_id, season, episode)
|
| 582 |
|
|
|
|
| 583 |
credits = getattr(tv, "credits", None) or {}
|
| 584 |
cast_arr = getattr(credits, "cast", []) or []
|
| 585 |
cast = [
|
|
|
|
| 587 |
for c in cast_arr
|
| 588 |
]
|
| 589 |
|
|
|
|
| 590 |
ep_runtime = getattr(ep, "runtime", None) if ep else None
|
| 591 |
+
series_runtime = tv.episode_run_time[0] if getattr(tv, "episode_run_time", None) else None
|
|
|
|
|
|
|
| 592 |
runtime_val = ep_runtime or series_runtime
|
| 593 |
runtime = f"{runtime_val} min" if runtime_val else ""
|
| 594 |
|
|
|
|
| 606 |
"media_type": "tv",
|
| 607 |
"cast": cast,
|
| 608 |
"runtime": str(runtime),
|
|
|
|
| 609 |
"season_number": season,
|
| 610 |
"episode_number": episode,
|
| 611 |
+
"episode_title": getattr(ep, "name", f"S{season:02d}E{episode:02d}") if ep else f"S{season:02d}E{episode:02d}",
|
| 612 |
"episode_backdrop": format_tmdb_image(getattr(ep, "still_path", None), "original") if ep else "",
|
| 613 |
"episode_overview": getattr(ep, "overview", "") if ep else "",
|
| 614 |
"episode_released": (
|
|
|
|
| 616 |
if getattr(ep, "air_date", None)
|
| 617 |
else ""
|
| 618 |
),
|
|
|
|
| 619 |
"quality": quality,
|
| 620 |
"encoded_string": encoded_string,
|
| 621 |
}
|
| 622 |
|
| 623 |
+
# ------------------------------------------------------------------
|
| 624 |
+
# 6. IMDb / Cinemeta path
|
| 625 |
+
# ------------------------------------------------------------------
|
| 626 |
imdb = imdb_tv or {}
|
| 627 |
ep = imdb_ep or {}
|
|
|
|
| 628 |
images = format_imdb_images(imdb_id)
|
| 629 |
|
| 630 |
return {
|
| 631 |
+
"tmdb_id": imdb.get("moviedb_id") or (imdb_id.replace("tt", "") if imdb_id else None),
|
| 632 |
"imdb_id": imdb_id,
|
| 633 |
"title": imdb.get("title", title),
|
| 634 |
"year": imdb.get("releaseDetailed", {}).get("year", 0),
|
|
|
|
| 638 |
"backdrop": images["backdrop"],
|
| 639 |
"logo": images["logo"],
|
| 640 |
"cast": imdb.get("cast", []),
|
| 641 |
+
"runtime": str(imdb.get("runtime") or ""),
|
| 642 |
"genres": imdb.get("genre", []),
|
| 643 |
"media_type": "tv",
|
|
|
|
| 644 |
"season_number": season,
|
| 645 |
"episode_number": episode,
|
| 646 |
+
"episode_title": ep.get("title", f"S{season:02d}E{episode:02d}"),
|
| 647 |
"episode_backdrop": ep.get("image", ""),
|
| 648 |
"episode_overview": ep.get("plot", ""),
|
| 649 |
"episode_released": str(ep.get("released", "")),
|
|
|
|
| 650 |
"quality": quality,
|
| 651 |
"encoded_string": encoded_string,
|
| 652 |
}
|
| 653 |
|
| 654 |
|
| 655 |
+
# =============================================================================
|
| 656 |
+
# Movie metadata
|
| 657 |
+
# =============================================================================
|
| 658 |
+
|
| 659 |
async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
|
| 660 |
imdb_id = None
|
| 661 |
tmdb_id = None
|
| 662 |
imdb_details = None
|
| 663 |
use_tmdb = False
|
| 664 |
|
| 665 |
+
# ------------------------------------------------------------------
|
| 666 |
+
# 1. Explicit default ID
|
| 667 |
+
# ------------------------------------------------------------------
|
| 668 |
if default_id:
|
| 669 |
default_id = str(default_id).strip()
|
|
|
|
| 670 |
if default_id.startswith("tt"):
|
| 671 |
imdb_id = default_id
|
|
|
|
| 672 |
elif default_id.isdigit():
|
| 673 |
tmdb_id = int(default_id)
|
| 674 |
+
use_tmdb = True
|
| 675 |
|
| 676 |
+
# ------------------------------------------------------------------
|
| 677 |
+
# 2. No ID → fuzzy Cinemeta search (tries year variants internally)
|
| 678 |
+
# ------------------------------------------------------------------
|
| 679 |
if not imdb_id and not tmdb_id:
|
| 680 |
+
imdb_id = await safe_imdb_search(title, "movie", year)
|
|
|
|
|
|
|
|
|
|
| 681 |
use_tmdb = not bool(imdb_id)
|
| 682 |
|
| 683 |
+
# ------------------------------------------------------------------
|
| 684 |
+
# 3. IMDb detail fetch
|
| 685 |
+
# ------------------------------------------------------------------
|
| 686 |
if imdb_id and not use_tmdb:
|
| 687 |
try:
|
| 688 |
+
if imdb_id in IMDB_CACHE and isinstance(IMDB_CACHE.get(imdb_id), dict):
|
| 689 |
imdb_details = IMDB_CACHE[imdb_id]
|
| 690 |
else:
|
| 691 |
async with API_SEMAPHORE:
|
| 692 |
+
imdb_details = await get_detail(imdb_id=imdb_id, media_type="movie")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 693 |
IMDB_CACHE[imdb_id] = imdb_details
|
| 694 |
|
| 695 |
except Exception as e:
|
|
|
|
| 697 |
imdb_details = None
|
| 698 |
use_tmdb = True
|
| 699 |
|
| 700 |
+
# ------------------------------------------------------------------
|
| 701 |
+
# 4. Validate IMDb result title against query
|
| 702 |
+
# ------------------------------------------------------------------
|
| 703 |
+
if imdb_details and not use_tmdb:
|
| 704 |
+
matched_title = imdb_details.get("title", "")
|
| 705 |
+
sim = _title_similarity(title, matched_title)
|
| 706 |
+
if sim < _CINEMETA_THRESHOLD:
|
| 707 |
+
LOGGER.info(
|
| 708 |
+
f"IMDb detail title mismatch for '{title}': "
|
| 709 |
+
f"got '{matched_title}' (sim={sim:.2f}) → switching to TMDb"
|
| 710 |
+
)
|
| 711 |
+
imdb_details = None
|
| 712 |
+
use_tmdb = True
|
| 713 |
+
|
| 714 |
+
# ------------------------------------------------------------------
|
| 715 |
+
# 5. Fallback: TMDb
|
| 716 |
+
# ------------------------------------------------------------------
|
| 717 |
+
must_use_tmdb = use_tmdb or not imdb_details
|
| 718 |
|
|
|
|
|
|
|
|
|
|
| 719 |
if must_use_tmdb:
|
| 720 |
+
LOGGER.info(f"No valid Cinemeta movie data for '{title}' (year={year}) → using TMDb")
|
| 721 |
|
|
|
|
| 722 |
if not tmdb_id:
|
| 723 |
tmdb_result = await safe_tmdb_search(title, "movie", year)
|
| 724 |
+
# Retry without year restriction for newer/unlisted titles
|
| 725 |
+
if not tmdb_result and year:
|
| 726 |
+
tmdb_result = await safe_tmdb_search(title, "movie", None)
|
| 727 |
+
|
| 728 |
if not tmdb_result:
|
| 729 |
+
LOGGER.info(
|
| 730 |
+
f"No TMDb movie found for '{title}' (year={year}) "
|
| 731 |
+
f"– metadata unavailable"
|
| 732 |
+
)
|
| 733 |
return None
|
| 734 |
tmdb_id = tmdb_result.id
|
| 735 |
|
|
|
|
| 736 |
movie = await _tmdb_movie_details(tmdb_id)
|
| 737 |
if not movie:
|
| 738 |
+
LOGGER.info(f"TMDb movie details failed for id={tmdb_id} ('{title}')")
|
| 739 |
return None
|
| 740 |
|
|
|
|
| 741 |
credits = getattr(movie, "credits", None) or {}
|
| 742 |
cast_arr = getattr(credits, "cast", []) or []
|
| 743 |
cast_names = [
|
|
|
|
| 766 |
"encoded_string": encoded_string,
|
| 767 |
}
|
| 768 |
|
| 769 |
+
# ------------------------------------------------------------------
|
| 770 |
+
# 6. IMDb / Cinemeta path
|
| 771 |
+
# ------------------------------------------------------------------
|
| 772 |
images = format_imdb_images(imdb_id)
|
| 773 |
imdb = imdb_details or {}
|
| 774 |
|
| 775 |
return {
|
| 776 |
+
"tmdb_id": imdb.get("moviedb_id") or (imdb_id.replace("tt", "") if imdb_id else None),
|
| 777 |
"imdb_id": imdb_id,
|
| 778 |
"title": imdb.get("title", title),
|
| 779 |
"year": imdb.get("releaseDetailed", {}).get("year", 0),
|
|
|
|
| 791 |
}
|
| 792 |
|
| 793 |
|
| 794 |
+
# =============================================================================
|
| 795 |
+
# Candidate-search helpers (used by the /set command UI)
|
| 796 |
+
# =============================================================================
|
| 797 |
+
|
| 798 |
async def search_movie_candidates(query: str, year: int | None = None, limit: int = 8) -> list[dict]:
|
| 799 |
query = (query or "").strip()
|
| 800 |
if not query:
|
|
|
|
| 803 |
results: list[dict] = []
|
| 804 |
seen: set[tuple[str, str]] = set()
|
| 805 |
|
|
|
|
| 806 |
try:
|
| 807 |
imdb_result = await search_title(query=query, type="movie")
|
| 808 |
if imdb_result and imdb_result.get("id"):
|
|
|
|
| 822 |
except Exception as e:
|
| 823 |
LOGGER.warning(f"IMDb movie candidate search failed for '{query}': {e}")
|
| 824 |
|
|
|
|
| 825 |
try:
|
| 826 |
async with API_SEMAPHORE:
|
| 827 |
+
tmdb_results = (
|
| 828 |
+
await tmdb.search().movies(query=query, year=year)
|
| 829 |
+
if year
|
| 830 |
+
else await tmdb.search().movies(query=query)
|
| 831 |
+
)
|
| 832 |
|
| 833 |
for item in (tmdb_results or [])[:limit]:
|
| 834 |
tmdb_id = getattr(item, "id", None)
|
|
|
|
| 875 |
results: list[dict] = []
|
| 876 |
seen: set[tuple[str, str]] = set()
|
| 877 |
|
|
|
|
| 878 |
try:
|
| 879 |
imdb_result = await search_title(query=query, type="tvSeries")
|
| 880 |
if imdb_result and imdb_result.get("id"):
|
|
|
|
| 894 |
except Exception as e:
|
| 895 |
LOGGER.warning(f"IMDb TV candidate search failed for '{query}': {e}")
|
| 896 |
|
|
|
|
| 897 |
try:
|
| 898 |
async with API_SEMAPHORE:
|
| 899 |
tmdb_results = await tmdb.search().tv(query=query)
|
|
|
|
| 935 |
return results[:limit]
|
| 936 |
|
| 937 |
|
| 938 |
+
# =============================================================================
|
| 939 |
+
# Manual /set command helpers
|
| 940 |
+
# =============================================================================
|
| 941 |
+
|
| 942 |
async def fetch_selected_movie_metadata(selected_id: str) -> dict | None:
|
| 943 |
selected_id = str(selected_id).strip()
|
| 944 |
if not selected_id:
|
Backend/helper/pyro.py
CHANGED
|
@@ -13,8 +13,57 @@ from pyrogram.types import BotCommand
|
|
| 13 |
from pyrogram import enums
|
| 14 |
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def is_media(message):
|
| 17 |
-
return next(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
|
| 20 |
async def get_file_ids(client: Client, chat_id: int, message_id: int) -> Optional[FileId]:
|
|
@@ -22,53 +71,72 @@ async def get_file_ids(client: Client, chat_id: int, message_id: int) -> Optiona
|
|
| 22 |
message = await client.get_messages(chat_id, message_id)
|
| 23 |
if message.empty:
|
| 24 |
raise FIleNotFound("Message not found or empty")
|
| 25 |
-
|
| 26 |
if media := is_media(message):
|
| 27 |
file_id_obj = FileId.decode(media.file_id)
|
| 28 |
file_unique_id = media.file_unique_id
|
| 29 |
-
|
| 30 |
setattr(file_id_obj, 'file_name', getattr(media, 'file_name', ''))
|
| 31 |
setattr(file_id_obj, 'file_size', getattr(media, 'file_size', 0))
|
| 32 |
setattr(file_id_obj, 'mime_type', getattr(media, 'mime_type', ''))
|
| 33 |
setattr(file_id_obj, 'unique_id', file_unique_id)
|
| 34 |
-
|
| 35 |
return file_id_obj
|
| 36 |
else:
|
| 37 |
raise FIleNotFound("No supported media found in message")
|
| 38 |
except Exception as e:
|
| 39 |
LOGGER.error(f"Error getting file IDs: {e}")
|
| 40 |
raise
|
| 41 |
-
|
| 42 |
|
| 43 |
|
| 44 |
def get_readable_file_size(size_in_bytes):
|
| 45 |
size_in_bytes = int(size_in_bytes) if str(size_in_bytes).isdigit() else 0
|
| 46 |
if not size_in_bytes:
|
| 47 |
return '0B'
|
| 48 |
-
|
| 49 |
index, SIZE_UNITS = 0, ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
|
| 50 |
while size_in_bytes >= 1024 and index < len(SIZE_UNITS) - 1:
|
| 51 |
size_in_bytes /= 1024
|
| 52 |
index += 1
|
| 53 |
-
|
| 54 |
return f'{size_in_bytes:.2f}{SIZE_UNITS[index]}' if index > 0 else f'{size_in_bytes:.0f}B'
|
| 55 |
|
| 56 |
|
| 57 |
-
def clean_filename(filename):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
if not filename:
|
| 59 |
return "unknown_file"
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
|
| 74 |
def get_readable_time(seconds: int) -> str:
|
|
@@ -76,43 +144,41 @@ def get_readable_time(seconds: int) -> str:
|
|
| 76 |
readable_time = ""
|
| 77 |
time_list = []
|
| 78 |
time_suffix_list = ["s", "m", "h", " days"]
|
| 79 |
-
|
| 80 |
while count < 4:
|
| 81 |
count += 1
|
| 82 |
if count < 3:
|
| 83 |
remainder, result = divmod(seconds, 60)
|
| 84 |
else:
|
| 85 |
remainder, result = divmod(seconds, 24)
|
| 86 |
-
|
| 87 |
if seconds == 0 and remainder == 0:
|
| 88 |
break
|
| 89 |
-
|
| 90 |
time_list.append(int(result))
|
| 91 |
seconds = int(remainder)
|
| 92 |
-
|
| 93 |
for x in range(len(time_list)):
|
| 94 |
time_list[x] = str(time_list[x]) + time_suffix_list[x]
|
| 95 |
-
|
| 96 |
if len(time_list) == 4:
|
| 97 |
readable_time += time_list.pop() + ", "
|
| 98 |
-
|
| 99 |
time_list.reverse()
|
| 100 |
readable_time += ": ".join(time_list)
|
| 101 |
-
|
| 102 |
-
return readable_time
|
| 103 |
|
|
|
|
| 104 |
|
| 105 |
|
| 106 |
def remove_urls(text):
|
| 107 |
if not text:
|
| 108 |
return ""
|
| 109 |
-
|
| 110 |
url_pattern = r'\b(?:https?|ftp):\/\/[^\s/$.?#].[^\s]*'
|
| 111 |
text_without_urls = re.sub(url_pattern, '', text)
|
| 112 |
cleaned_text = re.sub(r'\s+', ' ', text_without_urls).strip()
|
| 113 |
-
|
| 114 |
-
return cleaned_text
|
| 115 |
|
|
|
|
| 116 |
|
| 117 |
|
| 118 |
async def restart_notification():
|
|
@@ -122,21 +188,29 @@ async def restart_notification():
|
|
| 122 |
async with aiopen(".restartmsg", "r") as f:
|
| 123 |
data = await f.readlines()
|
| 124 |
chat_id, msg_id = map(int, data)
|
| 125 |
-
|
| 126 |
try:
|
| 127 |
repo = Telegram.UPSTREAM_REPO.split('/')
|
| 128 |
UPSTREAM_REPO = f"https://github.com/{repo[-2]}/{repo[-1]}"
|
| 129 |
await StreamBot.edit_message_text(
|
| 130 |
chat_id=chat_id,
|
| 131 |
message_id=msg_id,
|
| 132 |
-
text=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
parse_mode=enums.ParseMode.HTML
|
| 134 |
)
|
| 135 |
except Exception as e:
|
| 136 |
LOGGER.error(f"Failed to edit restart message: {e}")
|
| 137 |
-
|
| 138 |
await aioremove(".restartmsg")
|
| 139 |
-
|
| 140 |
except Exception as e:
|
| 141 |
LOGGER.error(f"Error in restart_notification: {e}")
|
| 142 |
|
|
@@ -164,9 +238,8 @@ async def setup_bot_commands(bot: Client):
|
|
| 164 |
if current_commands:
|
| 165 |
LOGGER.info(f"Found {len(current_commands)} existing commands. Deleting them...")
|
| 166 |
await bot.set_bot_commands([])
|
| 167 |
-
|
| 168 |
await bot.set_bot_commands(commands)
|
| 169 |
LOGGER.info("Bot commands updated successfully.")
|
| 170 |
except Exception as e:
|
| 171 |
LOGGER.error(f"Error setting up bot commands: {e}")
|
| 172 |
-
|
|
|
|
| 13 |
from pyrogram import enums
|
| 14 |
|
| 15 |
|
| 16 |
+
# ---------------------------------------------------------------------------
|
| 17 |
+
# Pre-compiled patterns used in clean_filename
|
| 18 |
+
# ---------------------------------------------------------------------------
|
| 19 |
+
|
| 20 |
+
# Broad emoji / unicode-symbol regex (covers all major Unicode emoji blocks)
|
| 21 |
+
_EMOJI_PATTERN = re.compile(
|
| 22 |
+
"["
|
| 23 |
+
"\U0001F600-\U0001F64F" # emoticons
|
| 24 |
+
"\U0001F300-\U0001F5FF" # symbols & pictographs
|
| 25 |
+
"\U0001F680-\U0001F6FF" # transport & map
|
| 26 |
+
"\U0001F700-\U0001FAFF" # extended symbols (geometric, supplemental, etc.)
|
| 27 |
+
"\U00002702-\U000027B0" # dingbats
|
| 28 |
+
"\U000024C2-\U0001F251" # enclosed chars
|
| 29 |
+
"\u2600-\u26FF" # misc symbols (☆, ★, ☀, ©, ®, ™, …)
|
| 30 |
+
"\u2700-\u27BF" # dingbats block
|
| 31 |
+
"\uFE00-\uFE0F" # variation selectors
|
| 32 |
+
"\U0001F1E0-\U0001F1FF" # regional indicator / flag sequences
|
| 33 |
+
"]+",
|
| 34 |
+
re.UNICODE,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
# Decorative / non-filename characters that are not emojis but still break PTN
|
| 38 |
+
_DECORATION_PATTERN = re.compile(
|
| 39 |
+
r"[•·‣⁃◦⦿⦾❖✦✧✪✫✬✭✮★☆♦♣♠♥►◄→←↑↓»«|¦‖⟨⟩⌨⌚⌛⏰⏱⏲⏳✔✖✗✘✅❌❎⚠⛔🚫]+",
|
| 40 |
+
re.UNICODE,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
# Telegram / social-media channel tag patterns
|
| 44 |
+
_CHANNEL_TAG_PATTERN = re.compile(
|
| 45 |
+
r"_@[A-Za-z]+_|@[A-Za-z]+_|[\[\]\s@]*@[^.\s\[\]]+[\]\[\s@]*"
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
# Common audio/source tags that are *not* relevant to the title
|
| 49 |
+
_CODEC_TAG_PATTERN = re.compile(
|
| 50 |
+
r"(?<=\W)(org|AMZN|DDP|DD|NF|AAC|TVDL|5\.1|2\.1|2\.0|7\.0|7\.1|5\.0|~|\b\w+kbps\b)(?=\W)",
|
| 51 |
+
re.IGNORECASE,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
def is_media(message):
|
| 56 |
+
return next(
|
| 57 |
+
(
|
| 58 |
+
getattr(message, attr)
|
| 59 |
+
for attr in [
|
| 60 |
+
"document", "photo", "video", "audio",
|
| 61 |
+
"voice", "video_note", "sticker", "animation",
|
| 62 |
+
]
|
| 63 |
+
if getattr(message, attr)
|
| 64 |
+
),
|
| 65 |
+
None,
|
| 66 |
+
)
|
| 67 |
|
| 68 |
|
| 69 |
async def get_file_ids(client: Client, chat_id: int, message_id: int) -> Optional[FileId]:
|
|
|
|
| 71 |
message = await client.get_messages(chat_id, message_id)
|
| 72 |
if message.empty:
|
| 73 |
raise FIleNotFound("Message not found or empty")
|
| 74 |
+
|
| 75 |
if media := is_media(message):
|
| 76 |
file_id_obj = FileId.decode(media.file_id)
|
| 77 |
file_unique_id = media.file_unique_id
|
| 78 |
+
|
| 79 |
setattr(file_id_obj, 'file_name', getattr(media, 'file_name', ''))
|
| 80 |
setattr(file_id_obj, 'file_size', getattr(media, 'file_size', 0))
|
| 81 |
setattr(file_id_obj, 'mime_type', getattr(media, 'mime_type', ''))
|
| 82 |
setattr(file_id_obj, 'unique_id', file_unique_id)
|
| 83 |
+
|
| 84 |
return file_id_obj
|
| 85 |
else:
|
| 86 |
raise FIleNotFound("No supported media found in message")
|
| 87 |
except Exception as e:
|
| 88 |
LOGGER.error(f"Error getting file IDs: {e}")
|
| 89 |
raise
|
|
|
|
| 90 |
|
| 91 |
|
| 92 |
def get_readable_file_size(size_in_bytes):
|
| 93 |
size_in_bytes = int(size_in_bytes) if str(size_in_bytes).isdigit() else 0
|
| 94 |
if not size_in_bytes:
|
| 95 |
return '0B'
|
| 96 |
+
|
| 97 |
index, SIZE_UNITS = 0, ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
|
| 98 |
while size_in_bytes >= 1024 and index < len(SIZE_UNITS) - 1:
|
| 99 |
size_in_bytes /= 1024
|
| 100 |
index += 1
|
| 101 |
+
|
| 102 |
return f'{size_in_bytes:.2f}{SIZE_UNITS[index]}' if index > 0 else f'{size_in_bytes:.0f}B'
|
| 103 |
|
| 104 |
|
| 105 |
+
def clean_filename(filename: str) -> str:
|
| 106 |
+
"""
|
| 107 |
+
Sanitise a raw Telegram caption / file name so PTN can parse it correctly.
|
| 108 |
+
|
| 109 |
+
Processing order:
|
| 110 |
+
1. Strip emoji sequences (they silently confuse PTN)
|
| 111 |
+
2. Strip decorative unicode punctuation (•, ★, »…)
|
| 112 |
+
3. Replace non-ASCII characters that survived with spaces
|
| 113 |
+
4. Remove Telegram channel / username tags
|
| 114 |
+
5. Remove common audio/source codec tags
|
| 115 |
+
6. Collapse whitespace
|
| 116 |
+
"""
|
| 117 |
if not filename:
|
| 118 |
return "unknown_file"
|
| 119 |
+
|
| 120 |
+
# 1 – Remove emoji sequences
|
| 121 |
+
filename = _EMOJI_PATTERN.sub(" ", filename)
|
| 122 |
+
|
| 123 |
+
# 2 – Remove decorative unicode symbols
|
| 124 |
+
filename = _DECORATION_PATTERN.sub(" ", filename)
|
| 125 |
+
|
| 126 |
+
# 3 – Replace any remaining non-ASCII characters with a space.
|
| 127 |
+
# Keep standard filename-safe characters: alphanumerics, . - _ ( ) [ ] ' " , : ! ? & + @
|
| 128 |
+
filename = re.sub(r"[^\x20-\x7E]", " ", filename)
|
| 129 |
+
|
| 130 |
+
# 4 – Remove Telegram channel tags (@ChannelName_ etc.)
|
| 131 |
+
filename = _CHANNEL_TAG_PATTERN.sub("", filename)
|
| 132 |
+
|
| 133 |
+
# 5 – Remove codec / source tags that clutter the title region
|
| 134 |
+
filename = _CODEC_TAG_PATTERN.sub(" ", filename)
|
| 135 |
+
|
| 136 |
+
# 6 – Collapse multiple spaces; remove space before extension dot
|
| 137 |
+
filename = re.sub(r"\s+", " ", filename).strip().replace(" .", ".")
|
| 138 |
+
|
| 139 |
+
return filename if filename else "unknown_file"
|
| 140 |
|
| 141 |
|
| 142 |
def get_readable_time(seconds: int) -> str:
|
|
|
|
| 144 |
readable_time = ""
|
| 145 |
time_list = []
|
| 146 |
time_suffix_list = ["s", "m", "h", " days"]
|
| 147 |
+
|
| 148 |
while count < 4:
|
| 149 |
count += 1
|
| 150 |
if count < 3:
|
| 151 |
remainder, result = divmod(seconds, 60)
|
| 152 |
else:
|
| 153 |
remainder, result = divmod(seconds, 24)
|
| 154 |
+
|
| 155 |
if seconds == 0 and remainder == 0:
|
| 156 |
break
|
| 157 |
+
|
| 158 |
time_list.append(int(result))
|
| 159 |
seconds = int(remainder)
|
| 160 |
+
|
| 161 |
for x in range(len(time_list)):
|
| 162 |
time_list[x] = str(time_list[x]) + time_suffix_list[x]
|
| 163 |
+
|
| 164 |
if len(time_list) == 4:
|
| 165 |
readable_time += time_list.pop() + ", "
|
| 166 |
+
|
| 167 |
time_list.reverse()
|
| 168 |
readable_time += ": ".join(time_list)
|
|
|
|
|
|
|
| 169 |
|
| 170 |
+
return readable_time
|
| 171 |
|
| 172 |
|
| 173 |
def remove_urls(text):
|
| 174 |
if not text:
|
| 175 |
return ""
|
| 176 |
+
|
| 177 |
url_pattern = r'\b(?:https?|ftp):\/\/[^\s/$.?#].[^\s]*'
|
| 178 |
text_without_urls = re.sub(url_pattern, '', text)
|
| 179 |
cleaned_text = re.sub(r'\s+', ' ', text_without_urls).strip()
|
|
|
|
|
|
|
| 180 |
|
| 181 |
+
return cleaned_text
|
| 182 |
|
| 183 |
|
| 184 |
async def restart_notification():
|
|
|
|
| 188 |
async with aiopen(".restartmsg", "r") as f:
|
| 189 |
data = await f.readlines()
|
| 190 |
chat_id, msg_id = map(int, data)
|
| 191 |
+
|
| 192 |
try:
|
| 193 |
repo = Telegram.UPSTREAM_REPO.split('/')
|
| 194 |
UPSTREAM_REPO = f"https://github.com/{repo[-2]}/{repo[-1]}"
|
| 195 |
await StreamBot.edit_message_text(
|
| 196 |
chat_id=chat_id,
|
| 197 |
message_id=msg_id,
|
| 198 |
+
text=(
|
| 199 |
+
f"... ♻️ Restart Successfully...! \n\n"
|
| 200 |
+
f"Date: {now.strftime('%d/%m/%y')}\n"
|
| 201 |
+
f"Time: {now.strftime('%I:%M:%S %p')}\n"
|
| 202 |
+
f"TimeZone: {timezone.zone}\n\n"
|
| 203 |
+
f"Repo: {UPSTREAM_REPO}\n"
|
| 204 |
+
f"Branch: {Telegram.UPSTREAM_BRANCH}\n"
|
| 205 |
+
f"Version: {__version__}"
|
| 206 |
+
),
|
| 207 |
parse_mode=enums.ParseMode.HTML
|
| 208 |
)
|
| 209 |
except Exception as e:
|
| 210 |
LOGGER.error(f"Failed to edit restart message: {e}")
|
| 211 |
+
|
| 212 |
await aioremove(".restartmsg")
|
| 213 |
+
|
| 214 |
except Exception as e:
|
| 215 |
LOGGER.error(f"Error in restart_notification: {e}")
|
| 216 |
|
|
|
|
| 238 |
if current_commands:
|
| 239 |
LOGGER.info(f"Found {len(current_commands)} existing commands. Deleting them...")
|
| 240 |
await bot.set_bot_commands([])
|
| 241 |
+
|
| 242 |
await bot.set_bot_commands(commands)
|
| 243 |
LOGGER.info("Bot commands updated successfully.")
|
| 244 |
except Exception as e:
|
| 245 |
LOGGER.error(f"Error setting up bot commands: {e}")
|
|
|