Upload 8 files
Browse files- .dockerignore +5 -0
- .gitignore +6 -0
- Dockerfile +20 -0
- README.md +120 -5
- craftmovies.py +1837 -0
- main.py +353 -0
- requirements.txt +5 -0
- test_local.py +6 -0
.dockerignore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.env
|
| 4 |
+
.venv/
|
| 5 |
+
venv/
|
.gitignore
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.env
|
| 4 |
+
.venv/
|
| 5 |
+
venv/
|
| 6 |
+
.cache/
|
Dockerfile
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.12-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
ENV PYTHONDONTWRITEBYTECODE=1
|
| 6 |
+
ENV PYTHONUNBUFFERED=1
|
| 7 |
+
ENV CRAFTMOVIES_BASE_URL=https://streamimdb.ru
|
| 8 |
+
ENV CRAFTMOVIES_TIMEOUT=15
|
| 9 |
+
ENV CRAFTMOVIES_DEBUG=false
|
| 10 |
+
ENV CRAFTMOVIES_CACHE_TTL_SECONDS=300
|
| 11 |
+
ENV CRAFTMOVIES_CORS_ORIGINS=*
|
| 12 |
+
|
| 13 |
+
COPY requirements.txt .
|
| 14 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 15 |
+
|
| 16 |
+
COPY . .
|
| 17 |
+
|
| 18 |
+
EXPOSE 7860
|
| 19 |
+
|
| 20 |
+
CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
README.md
CHANGED
|
@@ -1,10 +1,125 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: CraftMovies API
|
| 3 |
+
emoji: 🎬
|
| 4 |
+
colorFrom: red
|
| 5 |
+
colorTo: gray
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
---
|
| 9 |
|
| 10 |
+
# CraftMovies API — Hugging Face Space
|
| 11 |
+
|
| 12 |
+
FastAPI backend for CraftMovies, ready for Hugging Face Spaces Docker hosting.
|
| 13 |
+
|
| 14 |
+
## What this API does
|
| 15 |
+
|
| 16 |
+
Returns JSON for:
|
| 17 |
+
|
| 18 |
+
- Search
|
| 19 |
+
- Search All: search + TV seasons + episode metadata
|
| 20 |
+
- Browse movies
|
| 21 |
+
- Browse TV
|
| 22 |
+
- Movie detail
|
| 23 |
+
- TV show detail
|
| 24 |
+
- Episode detail
|
| 25 |
+
- Visible iframe `embed_url`
|
| 26 |
+
|
| 27 |
+
## Important
|
| 28 |
+
|
| 29 |
+
This API returns metadata and visible iframe embed URLs only. It does **not** bypass DRM, decode protected players, break tokens, or extract hidden third-party footage URLs.
|
| 30 |
+
|
| 31 |
+
Use returned `embed_url` in an iframe:
|
| 32 |
+
|
| 33 |
+
```html
|
| 34 |
+
<iframe
|
| 35 |
+
src="EMBED_URL_HERE"
|
| 36 |
+
allow="autoplay; fullscreen; picture-in-picture; encrypted-media"
|
| 37 |
+
referrerpolicy="no-referrer"
|
| 38 |
+
allowfullscreen
|
| 39 |
+
></iframe>
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
## Hugging Face Space setup
|
| 43 |
+
|
| 44 |
+
Create a new Space:
|
| 45 |
+
|
| 46 |
+
1. Go to Hugging Face → Spaces
|
| 47 |
+
2. Create new Space
|
| 48 |
+
3. Choose **Docker**
|
| 49 |
+
4. Upload all files from this ZIP
|
| 50 |
+
5. Wait for build to finish
|
| 51 |
+
|
| 52 |
+
The API will run on port `7860`.
|
| 53 |
+
|
| 54 |
+
## Local test
|
| 55 |
+
|
| 56 |
+
```bash
|
| 57 |
+
pip install -r requirements.txt
|
| 58 |
+
python -m uvicorn main:app --host 0.0.0.0 --port 7860 --reload
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
Open:
|
| 62 |
+
|
| 63 |
+
```text
|
| 64 |
+
http://127.0.0.1:7860/docs
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
## Endpoints
|
| 68 |
+
|
| 69 |
+
```text
|
| 70 |
+
GET /
|
| 71 |
+
GET /health
|
| 72 |
+
GET /api/home
|
| 73 |
+
GET /api/search?q=lucifer
|
| 74 |
+
GET /api/search-all?q=lucifer&limit_tv=1&limit_episodes=5
|
| 75 |
+
GET /api/fetch-movies
|
| 76 |
+
GET /api/fetch-tv
|
| 77 |
+
GET /api/browse/movie
|
| 78 |
+
GET /api/browse/tv
|
| 79 |
+
GET /api/movie?url=/movie/5nspt-the-avengers-2012
|
| 80 |
+
GET /api/tv-show?url=/tv/56tj4-lucifer&limit_episodes=5
|
| 81 |
+
GET /api/episode?url=/tv/56tj4-lucifer/season/1/episode/3
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
## Main endpoint for app frontend
|
| 85 |
+
|
| 86 |
+
```text
|
| 87 |
+
GET /api/search-all?q=lucifer&limit_tv=1&limit_episodes=5
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
This does:
|
| 91 |
+
|
| 92 |
+
```text
|
| 93 |
+
search
|
| 94 |
+
→ detect movie/TV
|
| 95 |
+
→ expand TV show
|
| 96 |
+
→ extract seasons
|
| 97 |
+
→ fetch episode pages
|
| 98 |
+
→ return episode embed_url
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
## Environment variables
|
| 102 |
+
|
| 103 |
+
Optional variables in Space settings:
|
| 104 |
+
|
| 105 |
+
```env
|
| 106 |
+
CRAFTMOVIES_BASE_URL=https://streamimdb.ru
|
| 107 |
+
CRAFTMOVIES_TIMEOUT=15
|
| 108 |
+
CRAFTMOVIES_DEBUG=false
|
| 109 |
+
CRAFTMOVIES_CACHE_TTL_SECONDS=300
|
| 110 |
+
CRAFTMOVIES_CORS_ORIGINS=*
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
## CORS
|
| 114 |
+
|
| 115 |
+
Default allows all origins:
|
| 116 |
+
|
| 117 |
+
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
+
CraftMovies
|
| 4 |
+
===========
|
| 5 |
+
|
| 6 |
+
A single-file Python metadata extractor/API-style client for StreamIMDB-like pages.
|
| 7 |
+
|
| 8 |
+
Main goal
|
| 9 |
+
---------
|
| 10 |
+
Use one class, `CraftMovies`, to fetch structured JSON-ready data:
|
| 11 |
+
|
| 12 |
+
from craftmovies import CraftMovies
|
| 13 |
+
|
| 14 |
+
cm = CraftMovies()
|
| 15 |
+
|
| 16 |
+
# Simple search only
|
| 17 |
+
data = cm.search("lucifer")
|
| 18 |
+
|
| 19 |
+
# One-call deep search: search + TV show seasons + all episodes + episode embed URLs
|
| 20 |
+
data = cm.searchAll("lucifer")
|
| 21 |
+
|
| 22 |
+
# Browse/trending/latest movies page
|
| 23 |
+
data = cm.fetchMovies()
|
| 24 |
+
|
| 25 |
+
# Direct detail pages
|
| 26 |
+
movie = cm.movie("/movie/5nspt-the-avengers-2012")
|
| 27 |
+
show = cm.tvShow("/tv/56tj4-lucifer", full=True)
|
| 28 |
+
ep = cm.episode("/tv/56tj4-lucifer/season/1/episode/3")
|
| 29 |
+
|
| 30 |
+
Important safety/behavior
|
| 31 |
+
-------------------------
|
| 32 |
+
This program extracts metadata and URLs visible in normal HTML only:
|
| 33 |
+
- title, year, posters, backdrops, descriptions
|
| 34 |
+
- categories/genres
|
| 35 |
+
- search cards
|
| 36 |
+
- movie metadata
|
| 37 |
+
- TV show seasons/episode links
|
| 38 |
+
- episode metadata
|
| 39 |
+
- iframe embed URLs such as /embed/movie/... or /embed/tv/...
|
| 40 |
+
- normal HTML <video>/<source>/<track> URLs if they are present in the HTML
|
| 41 |
+
|
| 42 |
+
It does NOT:
|
| 43 |
+
- bypass DRM
|
| 44 |
+
- decode protected/obfuscated player JavaScript
|
| 45 |
+
- break tokens
|
| 46 |
+
- extract hidden third-party footage URLs
|
| 47 |
+
|
| 48 |
+
Install
|
| 49 |
+
-------
|
| 50 |
+
pip install requests beautifulsoup4
|
| 51 |
+
|
| 52 |
+
CLI quick usage
|
| 53 |
+
---------------
|
| 54 |
+
python craftmovies.py --pretty search lucifer
|
| 55 |
+
python craftmovies.py --pretty search-all lucifer
|
| 56 |
+
python craftmovies.py --pretty search-all lucifer --limit-tv 1 --limit-episodes 5
|
| 57 |
+
python craftmovies.py --pretty fetch-movies
|
| 58 |
+
python craftmovies.py --pretty browse movie
|
| 59 |
+
python craftmovies.py --pretty movie https://streamimdb.ru/movie/5nspt-the-avengers-2012
|
| 60 |
+
python craftmovies.py --pretty tv https://streamimdb.ru/tv/56tj4-lucifer --full
|
| 61 |
+
python craftmovies.py --pretty episode https://streamimdb.ru/tv/56tj4-lucifer/season/1/episode/3
|
| 62 |
+
|
| 63 |
+
Expected output shape
|
| 64 |
+
---------------------
|
| 65 |
+
1) search(query)
|
| 66 |
+
|
| 67 |
+
{
|
| 68 |
+
"type": "search",
|
| 69 |
+
"query": "lucifer",
|
| 70 |
+
"summary": {"total_results": 9, "movies": 7, "tv_shows": 2},
|
| 71 |
+
"results": [
|
| 72 |
+
{
|
| 73 |
+
"title": "Lucifer",
|
| 74 |
+
"type": "tv",
|
| 75 |
+
"detail_url": "https://streamimdb.ru/tv/56tj4-lucifer",
|
| 76 |
+
"poster": "...",
|
| 77 |
+
"year": 2016
|
| 78 |
+
}
|
| 79 |
+
]
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
2) searchAll(query)
|
| 83 |
+
|
| 84 |
+
{
|
| 85 |
+
"type": "search_all",
|
| 86 |
+
"query": "lucifer",
|
| 87 |
+
"search": {...},
|
| 88 |
+
"movies": [
|
| 89 |
+
{"search_result": {...}}
|
| 90 |
+
],
|
| 91 |
+
"tv_shows": [
|
| 92 |
+
{
|
| 93 |
+
"search_result": {...},
|
| 94 |
+
"show": {
|
| 95 |
+
"show": {...},
|
| 96 |
+
"seasons": [
|
| 97 |
+
{
|
| 98 |
+
"season_number": 1,
|
| 99 |
+
"episode_count": 13,
|
| 100 |
+
"episodes": [...]
|
| 101 |
+
}
|
| 102 |
+
],
|
| 103 |
+
"episode_details": [
|
| 104 |
+
{
|
| 105 |
+
"episode": {...},
|
| 106 |
+
"video": {
|
| 107 |
+
"embed_url": "https://streamimdb.ru/embed/tv/63174/1/3"
|
| 108 |
+
}
|
| 109 |
+
}
|
| 110 |
+
]
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
]
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
3) fetchMovies()
|
| 117 |
+
|
| 118 |
+
{
|
| 119 |
+
"type": "browse",
|
| 120 |
+
"media_type": "movie",
|
| 121 |
+
"categories": [
|
| 122 |
+
{
|
| 123 |
+
"genre": "Action",
|
| 124 |
+
"see_all_url": "https://streamimdb.ru/category/action",
|
| 125 |
+
"items": [
|
| 126 |
+
{
|
| 127 |
+
"title": "Fuze",
|
| 128 |
+
"type": "movie",
|
| 129 |
+
"year": 2026,
|
| 130 |
+
"detail_url": "...",
|
| 131 |
+
"poster": "...",
|
| 132 |
+
"plot": "..."
|
| 133 |
+
}
|
| 134 |
+
]
|
| 135 |
+
}
|
| 136 |
+
],
|
| 137 |
+
"all_items_flat": [...]
|
| 138 |
+
}
|
| 139 |
+
"""
|
| 140 |
+
|
| 141 |
+
from __future__ import annotations
|
| 142 |
+
|
| 143 |
+
import argparse
|
| 144 |
+
import html
|
| 145 |
+
import json
|
| 146 |
+
import re
|
| 147 |
+
import sys
|
| 148 |
+
import time
|
| 149 |
+
from dataclasses import dataclass
|
| 150 |
+
from typing import Any, Optional
|
| 151 |
+
from urllib.parse import quote_plus, urljoin, urlparse
|
| 152 |
+
|
| 153 |
+
import requests
|
| 154 |
+
from bs4 import BeautifulSoup, Tag
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
MEDIA_EXTENSIONS = (".mp4", ".webm", ".ogg", ".m3u8", ".mpd", ".mov", ".m4v")
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@dataclass
|
| 161 |
+
class CraftMoviesConfig:
|
| 162 |
+
"""
|
| 163 |
+
Configuration for CraftMovies.
|
| 164 |
+
|
| 165 |
+
Attributes:
|
| 166 |
+
base_url: Main site URL.
|
| 167 |
+
timeout: HTTP timeout in seconds.
|
| 168 |
+
sleep: Delay between auto-fetch requests in deep modes.
|
| 169 |
+
debug: If True, prints request/debug info to stderr.
|
| 170 |
+
user_agent: HTTP User-Agent header.
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
base_url: str = "https://streamimdb.ru"
|
| 174 |
+
timeout: int = 10
|
| 175 |
+
sleep: float = 0.25
|
| 176 |
+
debug: bool = False
|
| 177 |
+
user_agent: str = (
|
| 178 |
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 179 |
+
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 180 |
+
"Chrome/124.0 Safari/537.36"
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class CraftMovies:
|
| 185 |
+
"""
|
| 186 |
+
Main API-style client.
|
| 187 |
+
|
| 188 |
+
Public methods:
|
| 189 |
+
search(query)
|
| 190 |
+
Search only. Fast. Does not fetch detail pages.
|
| 191 |
+
|
| 192 |
+
searchAll(query)
|
| 193 |
+
Search + automatically expands TV results into full show data.
|
| 194 |
+
By default, it also fetches episode pages so embed URLs are included.
|
| 195 |
+
This is the simpler replacement for "deep_tv_episode_details" mode.
|
| 196 |
+
|
| 197 |
+
fetchMovies()
|
| 198 |
+
Fetches /browse/movie and returns categories/genre rows and movie cards.
|
| 199 |
+
|
| 200 |
+
browse(media_type)
|
| 201 |
+
Generic browse function. media_type can be "movie" or "tv".
|
| 202 |
+
|
| 203 |
+
movie(url_or_path)
|
| 204 |
+
Extract a movie detail page.
|
| 205 |
+
|
| 206 |
+
tvShow(url_or_path, full=True)
|
| 207 |
+
Extract a TV show page. full=True fetches episode pages too.
|
| 208 |
+
|
| 209 |
+
episode(url_or_path)
|
| 210 |
+
Extract one episode page.
|
| 211 |
+
|
| 212 |
+
home()
|
| 213 |
+
Extract home page.
|
| 214 |
+
"""
|
| 215 |
+
|
| 216 |
+
def __init__(self, config: Optional[CraftMoviesConfig] = None):
|
| 217 |
+
self.config = config or CraftMoviesConfig()
|
| 218 |
+
self.session = requests.Session()
|
| 219 |
+
self.session.headers.update(
|
| 220 |
+
{
|
| 221 |
+
"User-Agent": self.config.user_agent,
|
| 222 |
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
| 223 |
+
"Accept-Language": "en-US,en;q=0.9",
|
| 224 |
+
}
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
# ======================================================================
|
| 228 |
+
# Public one-call methods
|
| 229 |
+
# ======================================================================
|
| 230 |
+
|
| 231 |
+
def searchAll(
|
| 232 |
+
self,
|
| 233 |
+
query: str,
|
| 234 |
+
*,
|
| 235 |
+
include_episode_details: bool = True,
|
| 236 |
+
limit_tv: int = 0,
|
| 237 |
+
limit_episodes: int = 0,
|
| 238 |
+
) -> dict[str, Any]:
|
| 239 |
+
"""
|
| 240 |
+
One-call full search.
|
| 241 |
+
|
| 242 |
+
This is the simplified "deep TV episode details" mode.
|
| 243 |
+
|
| 244 |
+
Flow:
|
| 245 |
+
1. Search once using /search?q=<query>.
|
| 246 |
+
2. Detect each result as movie or TV using the site's href/badge.
|
| 247 |
+
3. Keep movie cards as movie search results.
|
| 248 |
+
4. For each TV result:
|
| 249 |
+
- fetch the TV show page
|
| 250 |
+
- extract show metadata
|
| 251 |
+
- extract seasons
|
| 252 |
+
- extract all episode links grouped by season
|
| 253 |
+
- if include_episode_details=True, fetch episode pages too
|
| 254 |
+
and add episode metadata + embed URLs
|
| 255 |
+
|
| 256 |
+
Args:
|
| 257 |
+
query:
|
| 258 |
+
Search term, for example "lucifer".
|
| 259 |
+
include_episode_details:
|
| 260 |
+
True by default. Fetches each episode page for full metadata.
|
| 261 |
+
limit_tv:
|
| 262 |
+
Max TV shows to expand. 0 means all TV results.
|
| 263 |
+
limit_episodes:
|
| 264 |
+
Max episode pages fetched per show. 0 means all episodes.
|
| 265 |
+
|
| 266 |
+
Returns:
|
| 267 |
+
JSON-ready dict containing original search + expanded movie/TV data.
|
| 268 |
+
"""
|
| 269 |
+
|
| 270 |
+
search_data = self.search(query)
|
| 271 |
+
movie_results = [x for x in search_data["results"] if x.get("type") == "movie"]
|
| 272 |
+
tv_results = [x for x in search_data["results"] if x.get("type") == "tv"]
|
| 273 |
+
|
| 274 |
+
if limit_tv > 0:
|
| 275 |
+
tv_results = tv_results[:limit_tv]
|
| 276 |
+
|
| 277 |
+
expanded_tv = []
|
| 278 |
+
for tv_result in tv_results:
|
| 279 |
+
try:
|
| 280 |
+
time.sleep(self.config.sleep)
|
| 281 |
+
show_data = self.tvShow(
|
| 282 |
+
tv_result["detail_url"],
|
| 283 |
+
full=include_episode_details,
|
| 284 |
+
limit_episodes=limit_episodes,
|
| 285 |
+
)
|
| 286 |
+
expanded_tv.append(
|
| 287 |
+
{
|
| 288 |
+
"search_result": tv_result,
|
| 289 |
+
"show": show_data,
|
| 290 |
+
}
|
| 291 |
+
)
|
| 292 |
+
except Exception as exc:
|
| 293 |
+
expanded_tv.append(
|
| 294 |
+
{
|
| 295 |
+
"search_result": tv_result,
|
| 296 |
+
"error": str(exc),
|
| 297 |
+
}
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
return {
|
| 301 |
+
"type": "search_all",
|
| 302 |
+
"query": query,
|
| 303 |
+
"source_url": search_data.get("source_url"),
|
| 304 |
+
"search": search_data,
|
| 305 |
+
"movies": [{"search_result": item} for item in movie_results],
|
| 306 |
+
"tv_shows": expanded_tv,
|
| 307 |
+
"stats": {
|
| 308 |
+
"search_results": len(search_data.get("results", [])),
|
| 309 |
+
"movies": len(movie_results),
|
| 310 |
+
"tv_shows_found": len([x for x in search_data["results"] if x.get("type") == "tv"]),
|
| 311 |
+
"tv_shows_expanded": len(expanded_tv),
|
| 312 |
+
"episode_details_enabled": include_episode_details,
|
| 313 |
+
},
|
| 314 |
+
"extracted_at_unix": int(time.time()),
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
def fetchMovies(
|
| 318 |
+
self,
|
| 319 |
+
*,
|
| 320 |
+
include_details: bool = False,
|
| 321 |
+
limit_items: int = 0,
|
| 322 |
+
) -> dict[str, Any]:
|
| 323 |
+
"""
|
| 324 |
+
Fetch latest/trendy browse movies from /browse/movie.
|
| 325 |
+
|
| 326 |
+
This is an alias around:
|
| 327 |
+
browse("movie")
|
| 328 |
+
|
| 329 |
+
Args:
|
| 330 |
+
include_details:
|
| 331 |
+
If True, fetch every movie detail page too.
|
| 332 |
+
limit_items:
|
| 333 |
+
Max movie detail pages fetched when include_details=True.
|
| 334 |
+
0 means all visible items.
|
| 335 |
+
|
| 336 |
+
Returns:
|
| 337 |
+
Browse output with genre/category rows and movie cards.
|
| 338 |
+
"""
|
| 339 |
+
|
| 340 |
+
return self.browse(
|
| 341 |
+
"movie",
|
| 342 |
+
include_details=include_details,
|
| 343 |
+
limit_items=limit_items,
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
def fetchTV(
|
| 347 |
+
self,
|
| 348 |
+
*,
|
| 349 |
+
include_details: bool = False,
|
| 350 |
+
include_episode_details: bool = False,
|
| 351 |
+
limit_items: int = 0,
|
| 352 |
+
limit_episodes: int = 0,
|
| 353 |
+
) -> dict[str, Any]:
|
| 354 |
+
"""
|
| 355 |
+
Fetch browse TV rows from /browse/tv.
|
| 356 |
+
|
| 357 |
+
Args:
|
| 358 |
+
include_details:
|
| 359 |
+
If True, fetch each TV show detail page.
|
| 360 |
+
include_episode_details:
|
| 361 |
+
If True and include_details=True, fetch episode pages too.
|
| 362 |
+
limit_items:
|
| 363 |
+
Max TV show pages fetched.
|
| 364 |
+
limit_episodes:
|
| 365 |
+
Max episode pages fetched per show.
|
| 366 |
+
"""
|
| 367 |
+
|
| 368 |
+
return self.browse(
|
| 369 |
+
"tv",
|
| 370 |
+
include_details=include_details,
|
| 371 |
+
include_episode_details=include_episode_details,
|
| 372 |
+
limit_items=limit_items,
|
| 373 |
+
limit_episodes=limit_episodes,
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
# ======================================================================
|
| 377 |
+
# Public normal methods
|
| 378 |
+
# ======================================================================
|
| 379 |
+
|
| 380 |
+
def search(self, query: str, *, html_text: Optional[str] = None) -> dict[str, Any]:
|
| 381 |
+
"""
|
| 382 |
+
Search movies and TV shows.
|
| 383 |
+
|
| 384 |
+
Fast mode: only parses the search page, not detail pages.
|
| 385 |
+
Use searchAll(query) when you want everything in one call.
|
| 386 |
+
"""
|
| 387 |
+
|
| 388 |
+
url = self.abs_url(f"/search?q={quote_plus(query)}")
|
| 389 |
+
html_text = html_text if html_text is not None else self.fetch_html(url)
|
| 390 |
+
soup = BeautifulSoup(html_text, "html.parser")
|
| 391 |
+
|
| 392 |
+
results = []
|
| 393 |
+
for index, card in enumerate(soup.select(".cb-card-grid .cb-card, .cb-card")):
|
| 394 |
+
item = self._extract_card(card)
|
| 395 |
+
if item:
|
| 396 |
+
item["index"] = index + 1
|
| 397 |
+
results.append(item)
|
| 398 |
+
|
| 399 |
+
counts = self._extract_search_counts(soup)
|
| 400 |
+
|
| 401 |
+
return {
|
| 402 |
+
"type": "search",
|
| 403 |
+
"query": query,
|
| 404 |
+
"source_url": url,
|
| 405 |
+
"page": self.extract_page_meta(soup),
|
| 406 |
+
"summary": {
|
| 407 |
+
"title_text": self.text(soup.select_one(".cb-search-results-title")),
|
| 408 |
+
"total_results": counts.get("total"),
|
| 409 |
+
"movies": counts.get("movies"),
|
| 410 |
+
"tv_shows": counts.get("tv_shows"),
|
| 411 |
+
"parsed_results": len(results),
|
| 412 |
+
},
|
| 413 |
+
"results": self.dedupe_by(results, "detail_url"),
|
| 414 |
+
"pagination": self.extract_pagination(soup),
|
| 415 |
+
"all_embed_urls": self.extract_embed_urls(soup),
|
| 416 |
+
"json_ld": self.extract_json_ld(soup),
|
| 417 |
+
"extracted_at_unix": int(time.time()),
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
def browse(
|
| 421 |
+
self,
|
| 422 |
+
media_type: str = "movie",
|
| 423 |
+
*,
|
| 424 |
+
include_details: bool = False,
|
| 425 |
+
include_episode_details: bool = False,
|
| 426 |
+
limit_items: int = 0,
|
| 427 |
+
limit_episodes: int = 0,
|
| 428 |
+
html_text: Optional[str] = None,
|
| 429 |
+
) -> dict[str, Any]:
|
| 430 |
+
"""
|
| 431 |
+
Browse categories/genre rows.
|
| 432 |
+
|
| 433 |
+
Args:
|
| 434 |
+
media_type:
|
| 435 |
+
"movie" for /browse/movie or "tv" for /browse/tv.
|
| 436 |
+
include_details:
|
| 437 |
+
If True, fetch detail pages for all visible cards.
|
| 438 |
+
include_episode_details:
|
| 439 |
+
If True and media_type="tv", fetch episode pages too.
|
| 440 |
+
limit_items:
|
| 441 |
+
Max detail pages to fetch if include_details=True.
|
| 442 |
+
limit_episodes:
|
| 443 |
+
Max episode pages fetched per TV show.
|
| 444 |
+
html_text:
|
| 445 |
+
Optional local HTML for testing.
|
| 446 |
+
|
| 447 |
+
Returns:
|
| 448 |
+
Dict with:
|
| 449 |
+
- nav genre pills
|
| 450 |
+
- categories/genre sections
|
| 451 |
+
- all_items_flat
|
| 452 |
+
- optional detail_pages
|
| 453 |
+
"""
|
| 454 |
+
|
| 455 |
+
media_type = media_type.strip().lower()
|
| 456 |
+
if media_type in {"movies", "film", "films"}:
|
| 457 |
+
media_type = "movie"
|
| 458 |
+
if media_type in {"show", "shows", "series", "tv-shows"}:
|
| 459 |
+
media_type = "tv"
|
| 460 |
+
if media_type not in {"movie", "tv"}:
|
| 461 |
+
raise ValueError("media_type must be 'movie' or 'tv'")
|
| 462 |
+
|
| 463 |
+
path = f"/browse/{media_type}"
|
| 464 |
+
url = self.abs_url(path)
|
| 465 |
+
html_text = html_text if html_text is not None else self.fetch_html(url)
|
| 466 |
+
soup = BeautifulSoup(html_text, "html.parser")
|
| 467 |
+
|
| 468 |
+
genre_pills = self._extract_browse_genre_pills(soup)
|
| 469 |
+
categories = self._extract_browse_categories(soup)
|
| 470 |
+
flat_items = self._flatten_browse_items(categories)
|
| 471 |
+
|
| 472 |
+
detail_pages = []
|
| 473 |
+
if include_details:
|
| 474 |
+
target_items = flat_items[: limit_items or None]
|
| 475 |
+
for item in target_items:
|
| 476 |
+
try:
|
| 477 |
+
time.sleep(self.config.sleep)
|
| 478 |
+
if item.get("type") == "tv":
|
| 479 |
+
detail_pages.append(
|
| 480 |
+
self.tvShow(
|
| 481 |
+
item["detail_url"],
|
| 482 |
+
full=include_episode_details,
|
| 483 |
+
limit_episodes=limit_episodes,
|
| 484 |
+
)
|
| 485 |
+
)
|
| 486 |
+
else:
|
| 487 |
+
detail_pages.append(self.movie(item["detail_url"]))
|
| 488 |
+
except Exception as exc:
|
| 489 |
+
detail_pages.append({"source_item": item, "error": str(exc)})
|
| 490 |
+
|
| 491 |
+
return {
|
| 492 |
+
"type": "browse",
|
| 493 |
+
"media_type": media_type,
|
| 494 |
+
"source_url": url,
|
| 495 |
+
"page": self.extract_page_meta(soup),
|
| 496 |
+
"genre_pills": genre_pills,
|
| 497 |
+
"categories": categories,
|
| 498 |
+
"all_items_flat": flat_items,
|
| 499 |
+
"detail_pages": detail_pages,
|
| 500 |
+
"all_embed_urls": self.extract_embed_urls(soup),
|
| 501 |
+
"all_urls": self.extract_all_relevant_urls(soup),
|
| 502 |
+
"json_ld": self.extract_json_ld(soup),
|
| 503 |
+
"stats": {
|
| 504 |
+
"category_count": len(categories),
|
| 505 |
+
"flat_item_count": len(flat_items),
|
| 506 |
+
"detail_pages_fetched": len(detail_pages),
|
| 507 |
+
},
|
| 508 |
+
"extracted_at_unix": int(time.time()),
|
| 509 |
+
}
|
| 510 |
+
|
| 511 |
+
def home(self, *, html_text: Optional[str] = None) -> dict[str, Any]:
|
| 512 |
+
"""
|
| 513 |
+
Extract home page metadata and visible cards.
|
| 514 |
+
"""
|
| 515 |
+
|
| 516 |
+
url = self.abs_url("/")
|
| 517 |
+
html_text = html_text if html_text is not None else self.fetch_html(url)
|
| 518 |
+
soup = BeautifulSoup(html_text, "html.parser")
|
| 519 |
+
|
| 520 |
+
hero = self._extract_home_hero(soup)
|
| 521 |
+
top10 = self._extract_top10(soup)
|
| 522 |
+
sections = self._extract_home_sections(soup)
|
| 523 |
+
flat_items = self._flatten_home_items(hero, top10, sections)
|
| 524 |
+
all_embed_urls = self.dedupe_values(
|
| 525 |
+
[x.get("embed_url") for x in flat_items if x.get("embed_url")]
|
| 526 |
+
+ self.extract_embed_urls(soup)
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
return {
|
| 530 |
+
"type": "home",
|
| 531 |
+
"source_url": url,
|
| 532 |
+
"page": self.extract_page_meta(soup),
|
| 533 |
+
"navigation": self._extract_navigation(soup),
|
| 534 |
+
"hero": hero,
|
| 535 |
+
"top10": top10,
|
| 536 |
+
"sections": sections,
|
| 537 |
+
"all_items_flat": flat_items,
|
| 538 |
+
"all_embed_urls": all_embed_urls,
|
| 539 |
+
"stats": {
|
| 540 |
+
"hero_count": len(hero),
|
| 541 |
+
"top10_count": len(top10),
|
| 542 |
+
"section_count": len(sections),
|
| 543 |
+
"flat_item_count": len(flat_items),
|
| 544 |
+
"embed_url_count": len(all_embed_urls),
|
| 545 |
+
},
|
| 546 |
+
"extracted_at_unix": int(time.time()),
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
def movie(self, url_or_path: str, *, html_text: Optional[str] = None) -> dict[str, Any]:
|
| 550 |
+
"""
|
| 551 |
+
Extract metadata from a movie detail page.
|
| 552 |
+
"""
|
| 553 |
+
|
| 554 |
+
url = self.abs_url(url_or_path)
|
| 555 |
+
html_text = html_text if html_text is not None else self.fetch_html(url)
|
| 556 |
+
soup = BeautifulSoup(html_text, "html.parser")
|
| 557 |
+
|
| 558 |
+
player = soup.select_one("#cbMoviePlayer, iframe[data-src*='/embed/'], iframe[src*='/embed/']")
|
| 559 |
+
trailer = soup.select_one("#cbBgTrailer, iframe[src*='youtube.com/embed'], iframe[src*='youtu.be']")
|
| 560 |
+
|
| 561 |
+
meta_parts = [
|
| 562 |
+
self.text(span)
|
| 563 |
+
for span in soup.select(".cb-detail-meta-row .cb-meta-plain, .cb-detail-meta-row span")
|
| 564 |
+
if self.text(span) and self.text(span) != "·"
|
| 565 |
+
]
|
| 566 |
+
|
| 567 |
+
page_meta = self.extract_page_meta(soup)
|
| 568 |
+
title_logo = soup.select_one(".cb-detail-title-logo")
|
| 569 |
+
title = (
|
| 570 |
+
self.attr(title_logo, "alt")
|
| 571 |
+
or self.clean_movie_title_from_page(page_meta.get("title"))
|
| 572 |
+
or page_meta.get("og", {}).get("title")
|
| 573 |
+
)
|
| 574 |
+
|
| 575 |
+
player_path = self.attr(player, "data-src") or self.attr(player, "src")
|
| 576 |
+
player_url = self.abs_url(player_path)
|
| 577 |
+
all_embed_urls = self.dedupe_values(([player_url] if player_url else []) + self.extract_embed_urls(soup))
|
| 578 |
+
|
| 579 |
+
data = {
|
| 580 |
+
"type": "movie",
|
| 581 |
+
"source_url": url,
|
| 582 |
+
"page": page_meta,
|
| 583 |
+
"movie": {
|
| 584 |
+
"title": title,
|
| 585 |
+
"year": self.guess_year(" ".join(meta_parts) + " " + (title or "")),
|
| 586 |
+
"runtime": self.guess_runtime(meta_parts),
|
| 587 |
+
"genres": self.guess_genres(meta_parts),
|
| 588 |
+
"overview": self.text(soup.select_one("#cbPlot, .cb-detail-overview")),
|
| 589 |
+
"poster": page_meta.get("og", {}).get("image") or page_meta.get("twitter", {}).get("image"),
|
| 590 |
+
"backdrop": self.extract_background_image(soup.select_one(".cb-detail-banner-bg")),
|
| 591 |
+
"title_logo": self.abs_url(self.attr(title_logo, "src")),
|
| 592 |
+
"title_logo_alt": self.attr(title_logo, "alt"),
|
| 593 |
+
},
|
| 594 |
+
"video": {
|
| 595 |
+
"embed_path": player_path,
|
| 596 |
+
"embed_url": player_url,
|
| 597 |
+
"all_embed_urls": all_embed_urls,
|
| 598 |
+
"direct_video_url": None,
|
| 599 |
+
"direct_video_reason": "Direct footage URL is not present in normal movie page HTML.",
|
| 600 |
+
"trailer_url": self.attr(trailer, "src"),
|
| 601 |
+
"visible_html_media_urls": self.extract_visible_media_urls(soup),
|
| 602 |
+
},
|
| 603 |
+
"actors": self._extract_actors(soup),
|
| 604 |
+
"recommendations": self._extract_recommendations(soup),
|
| 605 |
+
"all_urls": self.extract_all_relevant_urls(soup),
|
| 606 |
+
"json_ld": self.extract_json_ld(soup),
|
| 607 |
+
"stats": {
|
| 608 |
+
"actors": len(self._extract_actors(soup)),
|
| 609 |
+
"recommendations": len(self._extract_recommendations(soup)),
|
| 610 |
+
"embed_urls": len(all_embed_urls),
|
| 611 |
+
},
|
| 612 |
+
"extracted_at_unix": int(time.time()),
|
| 613 |
+
}
|
| 614 |
+
|
| 615 |
+
return data
|
| 616 |
+
|
| 617 |
+
def tvShow(
|
| 618 |
+
self,
|
| 619 |
+
url_or_path: str,
|
| 620 |
+
*,
|
| 621 |
+
full: bool = True,
|
| 622 |
+
limit_episodes: int = 0,
|
| 623 |
+
html_text: Optional[str] = None,
|
| 624 |
+
) -> dict[str, Any]:
|
| 625 |
+
"""
|
| 626 |
+
Extract a TV show page.
|
| 627 |
+
|
| 628 |
+
Args:
|
| 629 |
+
full:
|
| 630 |
+
True by default. Fetches episode pages automatically for full
|
| 631 |
+
episode metadata and embed URLs.
|
| 632 |
+
limit_episodes:
|
| 633 |
+
Max episode pages fetched when full=True. 0 means all.
|
| 634 |
+
"""
|
| 635 |
+
|
| 636 |
+
url = self.abs_url(url_or_path)
|
| 637 |
+
html_text = html_text if html_text is not None else self.fetch_html(url)
|
| 638 |
+
soup = BeautifulSoup(html_text, "html.parser")
|
| 639 |
+
|
| 640 |
+
page_meta = self.extract_page_meta(soup)
|
| 641 |
+
title_logo = soup.select_one(".cb-detail-title-logo")
|
| 642 |
+
title = (
|
| 643 |
+
self.attr(title_logo, "alt")
|
| 644 |
+
or self.text(soup.select_one(".cb-detail-title, h1"))
|
| 645 |
+
or self.clean_tv_title_from_page(page_meta.get("title"))
|
| 646 |
+
or page_meta.get("og", {}).get("title")
|
| 647 |
+
)
|
| 648 |
+
|
| 649 |
+
meta_parts = [
|
| 650 |
+
self.text(span)
|
| 651 |
+
for span in soup.select(
|
| 652 |
+
".cb-detail-meta-row .cb-meta-plain, .cb-detail-meta-row span, .cb-detail-meta span, .cb-detail-meta-item"
|
| 653 |
+
)
|
| 654 |
+
if self.text(span) and self.text(span) != "·"
|
| 655 |
+
]
|
| 656 |
+
|
| 657 |
+
episodes_flat = self._extract_tv_episode_links(soup)
|
| 658 |
+
seasons = self._group_episodes_by_season(episodes_flat)
|
| 659 |
+
season_links = self._extract_tv_season_links(soup)
|
| 660 |
+
|
| 661 |
+
episode_details = []
|
| 662 |
+
if full:
|
| 663 |
+
target_episodes = episodes_flat[: limit_episodes or None]
|
| 664 |
+
for ep in target_episodes:
|
| 665 |
+
try:
|
| 666 |
+
time.sleep(self.config.sleep)
|
| 667 |
+
episode_details.append(self.episode(ep["episode_url"]))
|
| 668 |
+
except Exception as exc:
|
| 669 |
+
episode_details.append({"source_episode": ep, "error": str(exc)})
|
| 670 |
+
|
| 671 |
+
return {
|
| 672 |
+
"type": "tv_show",
|
| 673 |
+
"source_url": url,
|
| 674 |
+
"page": page_meta,
|
| 675 |
+
"show": {
|
| 676 |
+
"title": title,
|
| 677 |
+
"year": self.guess_year(" ".join(meta_parts) + " " + (title or "")),
|
| 678 |
+
"genres": self.guess_genres(meta_parts),
|
| 679 |
+
"overview": self.text(soup.select_one("#cbPlot, .cb-detail-overview, .cb-overview")),
|
| 680 |
+
"poster": page_meta.get("og", {}).get("image") or page_meta.get("twitter", {}).get("image"),
|
| 681 |
+
"backdrop": self.extract_background_image(
|
| 682 |
+
soup.select_one(".cb-detail-banner-bg, .cb-detail-backdrop")
|
| 683 |
+
),
|
| 684 |
+
"title_logo": self.abs_url(self.attr(title_logo, "src")),
|
| 685 |
+
"title_logo_alt": self.attr(title_logo, "alt"),
|
| 686 |
+
"meta_parts": meta_parts,
|
| 687 |
+
},
|
| 688 |
+
"season_links": season_links,
|
| 689 |
+
"seasons": seasons,
|
| 690 |
+
"episodes_flat": episodes_flat,
|
| 691 |
+
"episode_details": episode_details,
|
| 692 |
+
"actors": self._extract_actors(soup),
|
| 693 |
+
"recommendations": self._extract_recommendations(soup),
|
| 694 |
+
"all_embed_urls": self.extract_embed_urls(soup),
|
| 695 |
+
"all_urls": self.extract_all_relevant_urls(soup),
|
| 696 |
+
"json_ld": self.extract_json_ld(soup),
|
| 697 |
+
"stats": {
|
| 698 |
+
"season_count": len(seasons),
|
| 699 |
+
"episode_count": len(episodes_flat),
|
| 700 |
+
"episode_details_fetched": len(episode_details),
|
| 701 |
+
"actors": len(self._extract_actors(soup)),
|
| 702 |
+
"recommendations": len(self._extract_recommendations(soup)),
|
| 703 |
+
},
|
| 704 |
+
"extracted_at_unix": int(time.time()),
|
| 705 |
+
}
|
| 706 |
+
|
| 707 |
+
# Backward-compatible alias with snake_case.
|
| 708 |
+
def tv_show(self, url_or_path: str, **kwargs: Any) -> dict[str, Any]:
|
| 709 |
+
"""Alias for tvShow()."""
|
| 710 |
+
return self.tvShow(url_or_path, **kwargs)
|
| 711 |
+
|
| 712 |
+
def episode(self, url_or_path: str, *, html_text: Optional[str] = None) -> dict[str, Any]:
|
| 713 |
+
"""
|
| 714 |
+
Extract an individual TV episode page.
|
| 715 |
+
"""
|
| 716 |
+
|
| 717 |
+
url = self.abs_url(url_or_path)
|
| 718 |
+
html_text = html_text if html_text is not None else self.fetch_html(url)
|
| 719 |
+
soup = BeautifulSoup(html_text, "html.parser")
|
| 720 |
+
|
| 721 |
+
page_meta = self.extract_page_meta(soup)
|
| 722 |
+
player = soup.select_one("#cbEpisodePlayer, iframe[data-src*='/embed/tv'], iframe[src*='/embed/tv']")
|
| 723 |
+
player_path = self.attr(player, "data-src") or self.attr(player, "src")
|
| 724 |
+
player_url = self.abs_url(player_path)
|
| 725 |
+
|
| 726 |
+
show_link = soup.select_one(".cb-detail-title a[href*='/tv/'], .cb-breadcrumb a[href*='/tv/']")
|
| 727 |
+
center_title = self.text(soup.select_one(".cb-ep-title-center"))
|
| 728 |
+
h2_text = self.text(soup.select_one(".cb-detail-info h2"))
|
| 729 |
+
path_numbers = self.parse_episode_numbers_from_url(url)
|
| 730 |
+
episode_code = self.extract_episode_code(h2_text or center_title or page_meta.get("title") or "")
|
| 731 |
+
|
| 732 |
+
return {
|
| 733 |
+
"type": "episode",
|
| 734 |
+
"source_url": url,
|
| 735 |
+
"page": page_meta,
|
| 736 |
+
"episode": {
|
| 737 |
+
"show_title": self.text(show_link) or self.extract_show_title_from_episode_title(page_meta.get("title")),
|
| 738 |
+
"show_url": self.abs_url(self.attr(show_link, "href")),
|
| 739 |
+
"season_number": path_numbers.get("season"),
|
| 740 |
+
"episode_number": path_numbers.get("episode"),
|
| 741 |
+
"episode_code": episode_code,
|
| 742 |
+
"title": self.clean_episode_title(h2_text),
|
| 743 |
+
"air_date": self.extract_air_date(soup),
|
| 744 |
+
"overview": self.text(soup.select_one(".cb-detail-overview")),
|
| 745 |
+
"poster": self.abs_url(self.attr(soup.select_one(".cb-detail-poster img"), "src")),
|
| 746 |
+
"backdrop": self.extract_background_image(soup.select_one(".cb-detail-backdrop"))
|
| 747 |
+
or page_meta.get("og", {}).get("image"),
|
| 748 |
+
"hero_image": self.abs_url(self.attr(soup.select_one(".cb-poster-bg"), "src")),
|
| 749 |
+
},
|
| 750 |
+
"video": {
|
| 751 |
+
"embed_path": player_path,
|
| 752 |
+
"embed_url": player_url,
|
| 753 |
+
"all_embed_urls": self.dedupe_values(([player_url] if player_url else []) + self.extract_embed_urls(soup)),
|
| 754 |
+
"direct_video_url": None,
|
| 755 |
+
"direct_video_reason": "Direct footage URL is not present in normal episode page HTML.",
|
| 756 |
+
"visible_html_media_urls": self.extract_visible_media_urls(soup),
|
| 757 |
+
},
|
| 758 |
+
"navigation": self._extract_episode_navigation(soup),
|
| 759 |
+
"season_episodes": self._extract_episode_page_season_list(soup),
|
| 760 |
+
"all_urls": self.extract_all_relevant_urls(soup),
|
| 761 |
+
"json_ld": self.extract_json_ld(soup),
|
| 762 |
+
"stats": {
|
| 763 |
+
"season_episode_count": len(self._extract_episode_page_season_list(soup)),
|
| 764 |
+
"embed_urls": len(self.extract_embed_urls(soup)),
|
| 765 |
+
},
|
| 766 |
+
"extracted_at_unix": int(time.time()),
|
| 767 |
+
}
|
| 768 |
+
|
| 769 |
+
# ======================================================================
|
| 770 |
+
# Browse extraction helpers
|
| 771 |
+
# ======================================================================
|
| 772 |
+
|
| 773 |
+
def _extract_browse_genre_pills(self, soup: BeautifulSoup) -> list[dict[str, Any]]:
|
| 774 |
+
"""Extract sticky browse genre/type pills."""
|
| 775 |
+
|
| 776 |
+
pills = []
|
| 777 |
+
for a in soup.select(".cb-browse-nav a[href]"):
|
| 778 |
+
href = self.attr(a, "href")
|
| 779 |
+
label = self.text(a)
|
| 780 |
+
pills.append(
|
| 781 |
+
{
|
| 782 |
+
"label": label,
|
| 783 |
+
"genre": self.attr(a, "data-genre"),
|
| 784 |
+
"url": self.abs_url(href),
|
| 785 |
+
"path": href,
|
| 786 |
+
"active": "active" in (self.attr(a, "class") or ""),
|
| 787 |
+
"kind": "type" if "cb-browse-type-pill" in (self.attr(a, "class") or "") else "genre",
|
| 788 |
+
}
|
| 789 |
+
)
|
| 790 |
+
return self.dedupe_by(pills, "url")
|
| 791 |
+
|
| 792 |
+
def _extract_browse_categories(self, soup: BeautifulSoup) -> list[dict[str, Any]]:
|
| 793 |
+
"""Extract /browse/movie or /browse/tv genre rows."""
|
| 794 |
+
|
| 795 |
+
categories = []
|
| 796 |
+
for section_index, section in enumerate(soup.select(".cb-browse-genre-section, section.cb-row-section")):
|
| 797 |
+
genre = self.attr(section, "data-genre") or self.text(section.select_one(".cb-section-title"))
|
| 798 |
+
genre = self.clean_section_title(genre or "")
|
| 799 |
+
see_all = section.select_one(".cb-view-all[href]")
|
| 800 |
+
|
| 801 |
+
items = []
|
| 802 |
+
for idx, card in enumerate(section.select(".cb-card")):
|
| 803 |
+
item = self._extract_card(card)
|
| 804 |
+
if not item:
|
| 805 |
+
continue
|
| 806 |
+
item["index"] = idx + 1
|
| 807 |
+
item["genre"] = genre
|
| 808 |
+
items.append(item)
|
| 809 |
+
|
| 810 |
+
categories.append(
|
| 811 |
+
{
|
| 812 |
+
"index": section_index + 1,
|
| 813 |
+
"genre": genre,
|
| 814 |
+
"section_id": self.attr(section, "id"),
|
| 815 |
+
"see_all_url": self.abs_url(self.attr(see_all, "href")),
|
| 816 |
+
"see_all_path": self.attr(see_all, "href"),
|
| 817 |
+
"item_count": len(items),
|
| 818 |
+
"items": self.dedupe_by(items, "detail_url"),
|
| 819 |
+
}
|
| 820 |
+
)
|
| 821 |
+
|
| 822 |
+
return categories
|
| 823 |
+
|
| 824 |
+
def _flatten_browse_items(self, categories: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
| 825 |
+
"""Flatten browse categories while preserving genre membership."""
|
| 826 |
+
|
| 827 |
+
flat = []
|
| 828 |
+
seen = set()
|
| 829 |
+
|
| 830 |
+
for category in categories:
|
| 831 |
+
for item in category.get("items", []):
|
| 832 |
+
key = item.get("detail_url")
|
| 833 |
+
if not key:
|
| 834 |
+
continue
|
| 835 |
+
if key not in seen:
|
| 836 |
+
x = dict(item)
|
| 837 |
+
x["genres_found_in"] = [category.get("genre")]
|
| 838 |
+
flat.append(x)
|
| 839 |
+
seen.add(key)
|
| 840 |
+
else:
|
| 841 |
+
for existing in flat:
|
| 842 |
+
if existing.get("detail_url") == key:
|
| 843 |
+
existing.setdefault("genres_found_in", [])
|
| 844 |
+
if category.get("genre") not in existing["genres_found_in"]:
|
| 845 |
+
existing["genres_found_in"].append(category.get("genre"))
|
| 846 |
+
break
|
| 847 |
+
|
| 848 |
+
return flat
|
| 849 |
+
|
| 850 |
+
# ======================================================================
|
| 851 |
+
# Card/detail extraction helpers
|
| 852 |
+
# ======================================================================
|
| 853 |
+
|
| 854 |
+
def _extract_card(self, card: Tag) -> Optional[dict[str, Any]]:
|
| 855 |
+
"""Extract a movie/TV card from search, browse, listing, or rows."""
|
| 856 |
+
|
| 857 |
+
link = card.select_one("a[href]")
|
| 858 |
+
if not link:
|
| 859 |
+
return None
|
| 860 |
+
|
| 861 |
+
img = card.select_one(".cb-card-poster img, img")
|
| 862 |
+
badge = card.select_one(".cb-card-badge")
|
| 863 |
+
title_node = card.select_one(".cb-card-title, .cb-card-mc-title")
|
| 864 |
+
meta_node = card.select_one(".cb-card-meta, .cb-card-mc-meta")
|
| 865 |
+
plot_node = card.select_one(".cb-card-mc-plot")
|
| 866 |
+
play = card.select_one("[data-embed]")
|
| 867 |
+
|
| 868 |
+
href = self.attr(link, "href")
|
| 869 |
+
embed_path = self.attr(play, "data-embed")
|
| 870 |
+
|
| 871 |
+
title = (
|
| 872 |
+
self.attr(title_node, "title")
|
| 873 |
+
or self.text(title_node)
|
| 874 |
+
or self.attr(img, "alt")
|
| 875 |
+
or self.attr(link, "title")
|
| 876 |
+
)
|
| 877 |
+
meta = self.text(meta_node)
|
| 878 |
+
badge_text = self.text(badge)
|
| 879 |
+
|
| 880 |
+
return {
|
| 881 |
+
"title": title,
|
| 882 |
+
"type": self.detect_type(href, f"{badge_text or ''} {meta or ''}"),
|
| 883 |
+
"year": self.guess_year(meta or title or ""),
|
| 884 |
+
"detail_url": self.abs_url(href),
|
| 885 |
+
"path": href,
|
| 886 |
+
"embed_path": embed_path,
|
| 887 |
+
"embed_url": self.abs_url(embed_path),
|
| 888 |
+
"poster": self.abs_url(self.attr(img, "src")),
|
| 889 |
+
"poster_alt": self.attr(img, "alt"),
|
| 890 |
+
"badge": badge_text,
|
| 891 |
+
"meta": meta,
|
| 892 |
+
"plot": self.text(plot_node),
|
| 893 |
+
"image": {
|
| 894 |
+
"src": self.abs_url(self.attr(img, "src")),
|
| 895 |
+
"width": self.safe_int(self.attr(img, "width")),
|
| 896 |
+
"height": self.safe_int(self.attr(img, "height")),
|
| 897 |
+
"loading": self.attr(img, "loading"),
|
| 898 |
+
"decoding": self.attr(img, "decoding"),
|
| 899 |
+
},
|
| 900 |
+
}
|
| 901 |
+
|
| 902 |
+
def _extract_tv_episode_links(self, soup: BeautifulSoup) -> list[dict[str, Any]]:
|
| 903 |
+
"""Extract all visible /season/<n>/episode/<n> links from a TV show page."""
|
| 904 |
+
|
| 905 |
+
episodes = []
|
| 906 |
+
seen = set()
|
| 907 |
+
|
| 908 |
+
for a in soup.select("a[href*='/season/'][href*='/episode/']"):
|
| 909 |
+
href = self.attr(a, "href")
|
| 910 |
+
if not href:
|
| 911 |
+
continue
|
| 912 |
+
|
| 913 |
+
absolute = self.abs_url(href)
|
| 914 |
+
if absolute in seen:
|
| 915 |
+
continue
|
| 916 |
+
|
| 917 |
+
nums = self.parse_episode_numbers_from_url(href)
|
| 918 |
+
img = a.select_one("img")
|
| 919 |
+
title = (
|
| 920 |
+
self.text(a.select_one(".cb-episode-title, .episode-title, h3, h4"))
|
| 921 |
+
or self.attr(a, "title")
|
| 922 |
+
or self.attr(img, "alt")
|
| 923 |
+
or self.text(a)
|
| 924 |
+
)
|
| 925 |
+
|
| 926 |
+
date_text = self.text(a.select_one(".cb-episode-meta, .episode-meta, time"))
|
| 927 |
+
badge = self.text(a.select_one(".cb-episode-num, .episode-num"))
|
| 928 |
+
|
| 929 |
+
episodes.append(
|
| 930 |
+
{
|
| 931 |
+
"season_number": nums.get("season"),
|
| 932 |
+
"episode_number": nums.get("episode") or self.safe_int(badge),
|
| 933 |
+
"title": self.clean_episode_title(title),
|
| 934 |
+
"air_date": self.guess_date(date_text or ""),
|
| 935 |
+
"episode_url": absolute,
|
| 936 |
+
"episode_path": href,
|
| 937 |
+
"thumbnail": self.abs_url(self.attr(img, "src")),
|
| 938 |
+
"thumbnail_alt": self.attr(img, "alt"),
|
| 939 |
+
"raw_text": self.text(a),
|
| 940 |
+
}
|
| 941 |
+
)
|
| 942 |
+
seen.add(absolute)
|
| 943 |
+
|
| 944 |
+
episodes.sort(key=lambda x: (x.get("season_number") or 0, x.get("episode_number") or 0))
|
| 945 |
+
return episodes
|
| 946 |
+
|
| 947 |
+
def _group_episodes_by_season(self, episodes: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
| 948 |
+
"""Group episodes into seasons."""
|
| 949 |
+
|
| 950 |
+
grouped: dict[int, list[dict[str, Any]]] = {}
|
| 951 |
+
unknown = []
|
| 952 |
+
|
| 953 |
+
for ep in episodes:
|
| 954 |
+
season = ep.get("season_number")
|
| 955 |
+
if season is None:
|
| 956 |
+
unknown.append(ep)
|
| 957 |
+
continue
|
| 958 |
+
grouped.setdefault(season, []).append(ep)
|
| 959 |
+
|
| 960 |
+
seasons = []
|
| 961 |
+
for season_number in sorted(grouped):
|
| 962 |
+
eps = sorted(grouped[season_number], key=lambda x: x.get("episode_number") or 0)
|
| 963 |
+
seasons.append(
|
| 964 |
+
{
|
| 965 |
+
"season_number": season_number,
|
| 966 |
+
"episode_count": len(eps),
|
| 967 |
+
"episodes": eps,
|
| 968 |
+
}
|
| 969 |
+
)
|
| 970 |
+
|
| 971 |
+
if unknown:
|
| 972 |
+
seasons.append({"season_number": None, "episode_count": len(unknown), "episodes": unknown})
|
| 973 |
+
|
| 974 |
+
return seasons
|
| 975 |
+
|
| 976 |
+
def _extract_tv_season_links(self, soup: BeautifulSoup) -> list[dict[str, Any]]:
|
| 977 |
+
"""Extract season links/buttons if visible."""
|
| 978 |
+
|
| 979 |
+
links = []
|
| 980 |
+
for a in soup.select("a[href*='/season/']"):
|
| 981 |
+
href = self.attr(a, "href")
|
| 982 |
+
if not href or "/episode/" in href:
|
| 983 |
+
continue
|
| 984 |
+
nums = self.parse_episode_numbers_from_url(href)
|
| 985 |
+
links.append(
|
| 986 |
+
{
|
| 987 |
+
"season_number": nums.get("season"),
|
| 988 |
+
"label": self.text(a),
|
| 989 |
+
"url": self.abs_url(href),
|
| 990 |
+
"path": href,
|
| 991 |
+
}
|
| 992 |
+
)
|
| 993 |
+
return self.dedupe_by(links, "url")
|
| 994 |
+
|
| 995 |
+
def _extract_episode_page_season_list(self, soup: BeautifulSoup) -> list[dict[str, Any]]:
|
| 996 |
+
"""Extract mini episode list shown on episode pages."""
|
| 997 |
+
|
| 998 |
+
episodes = []
|
| 999 |
+
for item in soup.select(".cb-episode-list .cb-episode-item, a.cb-episode-item"):
|
| 1000 |
+
href = self.attr(item, "href")
|
| 1001 |
+
nums = self.parse_episode_numbers_from_url(href or "")
|
| 1002 |
+
episodes.append(
|
| 1003 |
+
{
|
| 1004 |
+
"season_number": nums.get("season"),
|
| 1005 |
+
"episode_number": nums.get("episode") or self.safe_int(self.text(item.select_one(".cb-episode-num"))),
|
| 1006 |
+
"title": self.text(item.select_one(".cb-episode-title")),
|
| 1007 |
+
"air_date": self.guess_date(self.text(item.select_one(".cb-episode-meta")) or ""),
|
| 1008 |
+
"episode_url": self.abs_url(href),
|
| 1009 |
+
"episode_path": href,
|
| 1010 |
+
"current": "current" in (self.attr(item, "class") or ""),
|
| 1011 |
+
}
|
| 1012 |
+
)
|
| 1013 |
+
return self.dedupe_by(episodes, "episode_url")
|
| 1014 |
+
|
| 1015 |
+
def _extract_episode_navigation(self, soup: BeautifulSoup) -> dict[str, Any]:
|
| 1016 |
+
"""Extract previous/next buttons from an episode page."""
|
| 1017 |
+
|
| 1018 |
+
previous_link = None
|
| 1019 |
+
next_link = None
|
| 1020 |
+
|
| 1021 |
+
for a in soup.select(".cb-episode-nav a[href], a.cb-ep-nav-btn[href]"):
|
| 1022 |
+
text_value = (self.text(a) or "").lower()
|
| 1023 |
+
item = {"label": self.text(a), "url": self.abs_url(self.attr(a, "href")), "path": self.attr(a, "href")}
|
| 1024 |
+
if "previous" in text_value:
|
| 1025 |
+
previous_link = item
|
| 1026 |
+
elif "next" in text_value:
|
| 1027 |
+
next_link = item
|
| 1028 |
+
|
| 1029 |
+
return {"previous": previous_link, "next": next_link}
|
| 1030 |
+
|
| 1031 |
+
def _extract_actors(self, soup: BeautifulSoup) -> list[dict[str, Any]]:
|
| 1032 |
+
"""Extract actor/cast cards."""
|
| 1033 |
+
|
| 1034 |
+
actors = []
|
| 1035 |
+
for index, item in enumerate(soup.select(".cb-cast-item-card")):
|
| 1036 |
+
img = item.select_one(".cb-cast-item-photo img")
|
| 1037 |
+
actors.append(
|
| 1038 |
+
{
|
| 1039 |
+
"index": index + 1,
|
| 1040 |
+
"name": self.text(item.select_one(".cb-cast-item-name")),
|
| 1041 |
+
"role": self.text(item.select_one(".cb-cast-item-role")),
|
| 1042 |
+
"profile_url": self.abs_url(self.attr(item, "href")),
|
| 1043 |
+
"profile_path": self.attr(item, "href"),
|
| 1044 |
+
"photo": self.abs_url(self.attr(img, "src")),
|
| 1045 |
+
"photo_alt": self.attr(img, "alt"),
|
| 1046 |
+
"initials": self.text(item.select_one(".cb-cast-item-initials")),
|
| 1047 |
+
}
|
| 1048 |
+
)
|
| 1049 |
+
return actors
|
| 1050 |
+
|
| 1051 |
+
def _extract_recommendations(self, soup: BeautifulSoup) -> list[dict[str, Any]]:
|
| 1052 |
+
"""Extract similar/recommended items."""
|
| 1053 |
+
|
| 1054 |
+
recommendations = []
|
| 1055 |
+
for index, item in enumerate(soup.select(".cb-similar-item")):
|
| 1056 |
+
img = item.select_one(".cb-similar-thumb img, img")
|
| 1057 |
+
meta_spans = [self.text(x) for x in item.select(".cb-similar-meta span") if self.text(x)]
|
| 1058 |
+
href = self.attr(item, "href")
|
| 1059 |
+
play = item.select_one("[data-embed]")
|
| 1060 |
+
embed_path = self.attr(play, "data-embed")
|
| 1061 |
+
|
| 1062 |
+
recommendations.append(
|
| 1063 |
+
{
|
| 1064 |
+
"index": index + 1,
|
| 1065 |
+
"title": self.text(item.select_one(".cb-similar-title")) or self.attr(img, "alt"),
|
| 1066 |
+
"type": self.detect_type(href, " ".join(meta_spans)),
|
| 1067 |
+
"year": self.guess_year(" ".join(meta_spans)),
|
| 1068 |
+
"detail_url": self.abs_url(href),
|
| 1069 |
+
"path": href,
|
| 1070 |
+
"embed_path": embed_path,
|
| 1071 |
+
"embed_url": self.abs_url(embed_path),
|
| 1072 |
+
"thumbnail": self.abs_url(self.attr(img, "src")),
|
| 1073 |
+
"thumbnail_alt": self.attr(img, "alt"),
|
| 1074 |
+
"meta_parts": meta_spans,
|
| 1075 |
+
}
|
| 1076 |
+
)
|
| 1077 |
+
|
| 1078 |
+
return self.dedupe_by(recommendations, "detail_url")
|
| 1079 |
+
|
| 1080 |
+
def _extract_home_hero(self, soup: BeautifulSoup) -> list[dict[str, Any]]:
|
| 1081 |
+
"""Extract homepage hero slider."""
|
| 1082 |
+
|
| 1083 |
+
items = []
|
| 1084 |
+
for idx, slide in enumerate(soup.select(".cb-slide")):
|
| 1085 |
+
play = slide.select_one(".cb-slide-play[data-embed], button[data-embed], [data-embed]")
|
| 1086 |
+
detail = slide.select_one("a[href*='/movie/'], a[href*='/tv/']")
|
| 1087 |
+
logo = slide.select_one("img.cb-slide-title-logo, .cb-slide-content img")
|
| 1088 |
+
bg_node = slide.select_one(".cb-slide-bg")
|
| 1089 |
+
|
| 1090 |
+
embed_path = self.attr(play, "data-embed")
|
| 1091 |
+
href = self.attr(detail, "href")
|
| 1092 |
+
title = self.attr(play, "data-title") or self.attr(logo, "alt") or self.text(slide.select_one("h1,h2,h3"))
|
| 1093 |
+
|
| 1094 |
+
meta_parts = [
|
| 1095 |
+
self.text(span)
|
| 1096 |
+
for span in slide.select(".cb-slide-meta span")
|
| 1097 |
+
if self.text(span) and self.text(span) != "·"
|
| 1098 |
+
]
|
| 1099 |
+
|
| 1100 |
+
items.append(
|
| 1101 |
+
{
|
| 1102 |
+
"index": idx + 1,
|
| 1103 |
+
"title": title,
|
| 1104 |
+
"type": self.detect_type(href),
|
| 1105 |
+
"detail_url": self.abs_url(href),
|
| 1106 |
+
"path": href,
|
| 1107 |
+
"embed_path": embed_path,
|
| 1108 |
+
"embed_url": self.abs_url(embed_path),
|
| 1109 |
+
"title_logo": self.abs_url(self.attr(logo, "src")),
|
| 1110 |
+
"title_logo_alt": self.attr(logo, "alt"),
|
| 1111 |
+
"backdrop": self.extract_background_image(bg_node),
|
| 1112 |
+
"meta_parts": meta_parts,
|
| 1113 |
+
"genres": self.guess_genres(meta_parts),
|
| 1114 |
+
"year": self.guess_year(" ".join(meta_parts)),
|
| 1115 |
+
"rating": self.guess_rating(meta_parts),
|
| 1116 |
+
}
|
| 1117 |
+
)
|
| 1118 |
+
return items
|
| 1119 |
+
|
| 1120 |
+
def _extract_top10(self, soup: BeautifulSoup) -> list[dict[str, Any]]:
|
| 1121 |
+
"""Extract homepage TOP 10 row."""
|
| 1122 |
+
|
| 1123 |
+
items = []
|
| 1124 |
+
for idx, card in enumerate(soup.select(".cb-top10-item")):
|
| 1125 |
+
img = card.select_one("img")
|
| 1126 |
+
number = self.text(card.select_one(".cb-top10-number"))
|
| 1127 |
+
href = self.attr(card, "href")
|
| 1128 |
+
title = self.attr(card, "aria-label") or self.attr(img, "alt")
|
| 1129 |
+
if title and " - " in title:
|
| 1130 |
+
title = title.split(" - ", 1)[1].strip()
|
| 1131 |
+
|
| 1132 |
+
items.append(
|
| 1133 |
+
{
|
| 1134 |
+
"rank": self.safe_int(number) or idx + 1,
|
| 1135 |
+
"title": title,
|
| 1136 |
+
"type": self.detect_type(href),
|
| 1137 |
+
"detail_url": self.abs_url(href),
|
| 1138 |
+
"path": href,
|
| 1139 |
+
"poster": self.abs_url(self.attr(img, "src")),
|
| 1140 |
+
"poster_alt": self.attr(img, "alt"),
|
| 1141 |
+
"embed_path": None,
|
| 1142 |
+
"embed_url": None,
|
| 1143 |
+
}
|
| 1144 |
+
)
|
| 1145 |
+
return items
|
| 1146 |
+
|
| 1147 |
+
def _extract_home_sections(self, soup: BeautifulSoup) -> list[dict[str, Any]]:
|
| 1148 |
+
"""Extract homepage rows/sections."""
|
| 1149 |
+
|
| 1150 |
+
sections = []
|
| 1151 |
+
for section_index, section in enumerate(soup.select("section.cb-section")):
|
| 1152 |
+
title = self.text(section.select_one(".cb-section-title"))
|
| 1153 |
+
if not title:
|
| 1154 |
+
continue
|
| 1155 |
+
|
| 1156 |
+
section_data = {"index": section_index, "title": self.clean_section_title(title), "items": []}
|
| 1157 |
+
cards = []
|
| 1158 |
+
for card in section.select(".cb-card"):
|
| 1159 |
+
item = self._extract_card(card)
|
| 1160 |
+
if item:
|
| 1161 |
+
cards.append(item)
|
| 1162 |
+
section_data["items"] = self.dedupe_by(cards, "detail_url")
|
| 1163 |
+
if section_data["items"]:
|
| 1164 |
+
sections.append(section_data)
|
| 1165 |
+
return sections
|
| 1166 |
+
|
| 1167 |
+
def _flatten_home_items(
|
| 1168 |
+
self,
|
| 1169 |
+
hero: list[dict[str, Any]],
|
| 1170 |
+
top10: list[dict[str, Any]],
|
| 1171 |
+
sections: list[dict[str, Any]],
|
| 1172 |
+
) -> list[dict[str, Any]]:
|
| 1173 |
+
"""Flatten home page items."""
|
| 1174 |
+
|
| 1175 |
+
flat = []
|
| 1176 |
+
for item in hero:
|
| 1177 |
+
x = dict(item)
|
| 1178 |
+
x["source_section"] = "Hero"
|
| 1179 |
+
flat.append(x)
|
| 1180 |
+
for item in top10:
|
| 1181 |
+
x = dict(item)
|
| 1182 |
+
x["source_section"] = "TOP 10"
|
| 1183 |
+
flat.append(x)
|
| 1184 |
+
for section in sections:
|
| 1185 |
+
for item in section.get("items", []):
|
| 1186 |
+
x = dict(item)
|
| 1187 |
+
x["source_section"] = section.get("title")
|
| 1188 |
+
flat.append(x)
|
| 1189 |
+
return self.dedupe_by(flat, "detail_url")
|
| 1190 |
+
|
| 1191 |
+
def _extract_navigation(self, soup: BeautifulSoup) -> dict[str, Any]:
|
| 1192 |
+
"""Extract site navigation."""
|
| 1193 |
+
|
| 1194 |
+
main_links = []
|
| 1195 |
+
for a in soup.select("header a.cb-nav-link[href], .cb-mobile-nav a.cb-mobile-link[href], .cb-bottom-nav a[href]"):
|
| 1196 |
+
item = self.link_item(a)
|
| 1197 |
+
if item:
|
| 1198 |
+
main_links.append(item)
|
| 1199 |
+
|
| 1200 |
+
genres = []
|
| 1201 |
+
for a in soup.select("a[href^='/category/'], a[href*='/category/']"):
|
| 1202 |
+
item = self.link_item(a)
|
| 1203 |
+
if item:
|
| 1204 |
+
genres.append(item)
|
| 1205 |
+
|
| 1206 |
+
years = []
|
| 1207 |
+
for a in soup.select("a[href^='/year/'], a[href*='/year/']"):
|
| 1208 |
+
item = self.link_item(a)
|
| 1209 |
+
if item:
|
| 1210 |
+
years.append(item)
|
| 1211 |
+
|
| 1212 |
+
return {
|
| 1213 |
+
"main_links": self.dedupe_by(main_links, "url"),
|
| 1214 |
+
"genres": self.dedupe_by(genres, "url"),
|
| 1215 |
+
"years": self.dedupe_by(years, "url"),
|
| 1216 |
+
"search": {
|
| 1217 |
+
"action": self.abs_url(self.attr(soup.select_one("form.cb-search, form.cb-mobile-search"), "action")),
|
| 1218 |
+
"method": (self.attr(soup.select_one("form.cb-search, form.cb-mobile-search"), "method") or "GET").upper(),
|
| 1219 |
+
"query_param": "q",
|
| 1220 |
+
},
|
| 1221 |
+
}
|
| 1222 |
+
|
| 1223 |
+
def _extract_search_counts(self, soup: BeautifulSoup) -> dict[str, Optional[int]]:
|
| 1224 |
+
"""Parse search counts text."""
|
| 1225 |
+
|
| 1226 |
+
text_value = self.text(soup.select_one(".cb-search-results-title")) or ""
|
| 1227 |
+
total = movies = tv = None
|
| 1228 |
+
|
| 1229 |
+
m = re.search(r"(\d+)\s+results", text_value, flags=re.I)
|
| 1230 |
+
if m:
|
| 1231 |
+
total = int(m.group(1))
|
| 1232 |
+
m = re.search(r"(\d+)\s+movies", text_value, flags=re.I)
|
| 1233 |
+
if m:
|
| 1234 |
+
movies = int(m.group(1))
|
| 1235 |
+
m = re.search(r"(\d+)\s+TV\s+shows", text_value, flags=re.I)
|
| 1236 |
+
if m:
|
| 1237 |
+
tv = int(m.group(1))
|
| 1238 |
+
|
| 1239 |
+
return {"total": total, "movies": movies, "tv_shows": tv}
|
| 1240 |
+
|
| 1241 |
+
# ======================================================================
|
| 1242 |
+
# Shared URL/media/metadata helpers
|
| 1243 |
+
# ======================================================================
|
| 1244 |
+
|
| 1245 |
+
def fetch_html(self, url_or_path: str) -> str:
|
| 1246 |
+
"""Fetch HTML from same base domain."""
|
| 1247 |
+
|
| 1248 |
+
url = self.abs_url(url_or_path)
|
| 1249 |
+
self.ensure_same_domain(url)
|
| 1250 |
+
|
| 1251 |
+
if self.config.debug:
|
| 1252 |
+
print(f"[debug] Fetching {url}", file=sys.stderr, flush=True)
|
| 1253 |
+
|
| 1254 |
+
response = self.session.get(url, timeout=self.config.timeout)
|
| 1255 |
+
|
| 1256 |
+
if self.config.debug:
|
| 1257 |
+
print(
|
| 1258 |
+
f"[debug] Status={response.status_code} bytes={len(response.content)} "
|
| 1259 |
+
f"content-type={response.headers.get('content-type')}",
|
| 1260 |
+
file=sys.stderr,
|
| 1261 |
+
flush=True,
|
| 1262 |
+
)
|
| 1263 |
+
|
| 1264 |
+
response.raise_for_status()
|
| 1265 |
+
return response.text
|
| 1266 |
+
|
| 1267 |
+
def abs_url(self, value: Optional[str]) -> Optional[str]:
|
| 1268 |
+
"""Convert relative URL/path to absolute URL."""
|
| 1269 |
+
|
| 1270 |
+
if not value:
|
| 1271 |
+
return None
|
| 1272 |
+
return urljoin(self.config.base_url.rstrip("/") + "/", value)
|
| 1273 |
+
|
| 1274 |
+
def ensure_same_domain(self, url: str) -> None:
|
| 1275 |
+
"""Refuse to crawl external domains."""
|
| 1276 |
+
|
| 1277 |
+
base = urlparse(self.config.base_url)
|
| 1278 |
+
target = urlparse(url)
|
| 1279 |
+
if base.netloc and target.netloc and base.netloc != target.netloc:
|
| 1280 |
+
raise ValueError(f"External crawl blocked: {url}")
|
| 1281 |
+
|
| 1282 |
+
def extract_embed_urls(self, soup: BeautifulSoup) -> list[str]:
|
| 1283 |
+
"""Extract visible iframe/data-embed URLs."""
|
| 1284 |
+
|
| 1285 |
+
embeds = []
|
| 1286 |
+
for node in soup.select("[data-embed]"):
|
| 1287 |
+
embeds.append(self.abs_url(self.attr(node, "data-embed")))
|
| 1288 |
+
|
| 1289 |
+
for iframe in soup.select("iframe[src], iframe[data-src]"):
|
| 1290 |
+
src = self.attr(iframe, "data-src") or self.attr(iframe, "src")
|
| 1291 |
+
if src and "/embed/" in src:
|
| 1292 |
+
embeds.append(self.abs_url(src))
|
| 1293 |
+
|
| 1294 |
+
raw = str(soup)
|
| 1295 |
+
for match in re.findall(r"['\"](/embed/[^'\"\s<>]+)['\"]", raw):
|
| 1296 |
+
embeds.append(self.abs_url(match))
|
| 1297 |
+
|
| 1298 |
+
return self.dedupe_values([x for x in embeds if x])
|
| 1299 |
+
|
| 1300 |
+
def extract_visible_media_urls(self, soup: BeautifulSoup) -> list[dict[str, Any]]:
|
| 1301 |
+
"""Extract normal HTML media URLs only, if visible in HTML."""
|
| 1302 |
+
|
| 1303 |
+
media = []
|
| 1304 |
+
|
| 1305 |
+
for video in soup.select("video"):
|
| 1306 |
+
src = self.attr(video, "src")
|
| 1307 |
+
poster = self.attr(video, "poster")
|
| 1308 |
+
if src:
|
| 1309 |
+
media.append({"url": self.abs_url(src), "kind": "video", "source": "video[src]"})
|
| 1310 |
+
if poster:
|
| 1311 |
+
media.append({"url": self.abs_url(poster), "kind": "poster", "source": "video[poster]"})
|
| 1312 |
+
|
| 1313 |
+
for source in video.select("source[src]"):
|
| 1314 |
+
media.append(
|
| 1315 |
+
{
|
| 1316 |
+
"url": self.abs_url(self.attr(source, "src")),
|
| 1317 |
+
"kind": "source",
|
| 1318 |
+
"mime_type": self.attr(source, "type"),
|
| 1319 |
+
"source": "video source[src]",
|
| 1320 |
+
}
|
| 1321 |
+
)
|
| 1322 |
+
|
| 1323 |
+
for track in video.select("track[src]"):
|
| 1324 |
+
media.append(
|
| 1325 |
+
{
|
| 1326 |
+
"url": self.abs_url(self.attr(track, "src")),
|
| 1327 |
+
"kind": "subtitle",
|
| 1328 |
+
"label": self.attr(track, "label"),
|
| 1329 |
+
"srclang": self.attr(track, "srclang"),
|
| 1330 |
+
"source": "track[src]",
|
| 1331 |
+
}
|
| 1332 |
+
)
|
| 1333 |
+
|
| 1334 |
+
for source in soup.select("source[src]"):
|
| 1335 |
+
src = self.attr(source, "src")
|
| 1336 |
+
if src and self.looks_like_media(src):
|
| 1337 |
+
media.append(
|
| 1338 |
+
{
|
| 1339 |
+
"url": self.abs_url(src),
|
| 1340 |
+
"kind": "source",
|
| 1341 |
+
"mime_type": self.attr(source, "type"),
|
| 1342 |
+
"source": "source[src]",
|
| 1343 |
+
}
|
| 1344 |
+
)
|
| 1345 |
+
|
| 1346 |
+
for a in soup.select("a[href]"):
|
| 1347 |
+
href = self.attr(a, "href")
|
| 1348 |
+
if href and self.looks_like_media(href):
|
| 1349 |
+
media.append({"url": self.abs_url(href), "kind": "link", "source": "a[href]"})
|
| 1350 |
+
|
| 1351 |
+
for url in self.find_literal_media_urls(str(soup)):
|
| 1352 |
+
media.append({"url": self.abs_url(url), "kind": "literal", "source": "raw_html"})
|
| 1353 |
+
|
| 1354 |
+
return self.dedupe_by(media, "url")
|
| 1355 |
+
|
| 1356 |
+
def extract_all_relevant_urls(self, soup: BeautifulSoup) -> dict[str, list[str]]:
|
| 1357 |
+
"""Extract links, images, iframes, scripts, stylesheets, preloads, embeds, media literals."""
|
| 1358 |
+
|
| 1359 |
+
urls = {
|
| 1360 |
+
"links": [],
|
| 1361 |
+
"images": [],
|
| 1362 |
+
"iframes": [],
|
| 1363 |
+
"scripts": [],
|
| 1364 |
+
"stylesheets": [],
|
| 1365 |
+
"preloads": [],
|
| 1366 |
+
"embeds": [],
|
| 1367 |
+
"media_literals": [],
|
| 1368 |
+
}
|
| 1369 |
+
|
| 1370 |
+
for a in soup.select("a[href]"):
|
| 1371 |
+
urls["links"].append(self.abs_url(self.attr(a, "href")))
|
| 1372 |
+
|
| 1373 |
+
for img in soup.select("img[src], img[data-src]"):
|
| 1374 |
+
urls["images"].append(self.abs_url(self.attr(img, "src") or self.attr(img, "data-src")))
|
| 1375 |
+
|
| 1376 |
+
for iframe in soup.select("iframe[src], iframe[data-src]"):
|
| 1377 |
+
src = self.attr(iframe, "data-src") or self.attr(iframe, "src")
|
| 1378 |
+
urls["iframes"].append(self.abs_url(src))
|
| 1379 |
+
if src and "/embed/" in src:
|
| 1380 |
+
urls["embeds"].append(self.abs_url(src))
|
| 1381 |
+
|
| 1382 |
+
for node in soup.select("[data-embed]"):
|
| 1383 |
+
urls["embeds"].append(self.abs_url(self.attr(node, "data-embed")))
|
| 1384 |
+
|
| 1385 |
+
for script in soup.select("script[src]"):
|
| 1386 |
+
urls["scripts"].append(self.abs_url(self.attr(script, "src")))
|
| 1387 |
+
|
| 1388 |
+
for link in soup.select("link[href]"):
|
| 1389 |
+
rel = " ".join(link.get("rel", [])) if link.get("rel") else ""
|
| 1390 |
+
href = self.abs_url(self.attr(link, "href"))
|
| 1391 |
+
if "stylesheet" in rel:
|
| 1392 |
+
urls["stylesheets"].append(href)
|
| 1393 |
+
if "preload" in rel:
|
| 1394 |
+
urls["preloads"].append(href)
|
| 1395 |
+
|
| 1396 |
+
urls["media_literals"] = [self.abs_url(x) for x in self.find_literal_media_urls(str(soup))]
|
| 1397 |
+
urls["embeds"] = self.dedupe_values(urls["embeds"] + self.extract_embed_urls(soup))
|
| 1398 |
+
return {k: self.dedupe_values([x for x in v if x]) for k, v in urls.items()}
|
| 1399 |
+
|
| 1400 |
+
def extract_page_meta(self, soup: BeautifulSoup) -> dict[str, Any]:
|
| 1401 |
+
"""Extract SEO/OpenGraph/Twitter/basic page metadata."""
|
| 1402 |
+
|
| 1403 |
+
return {
|
| 1404 |
+
"title": self.text(soup.select_one("title")),
|
| 1405 |
+
"description": self.meta(soup, "meta[name='description']"),
|
| 1406 |
+
"canonical": self.abs_url(self.attr(soup.select_one("link[rel='canonical']"), "href")),
|
| 1407 |
+
"robots": self.meta(soup, "meta[name='robots']"),
|
| 1408 |
+
"theme_color": self.meta(soup, "meta[name='theme-color']"),
|
| 1409 |
+
"manifest": self.abs_url(self.attr(soup.select_one("link[rel='manifest']"), "href")),
|
| 1410 |
+
"og": {
|
| 1411 |
+
"title": self.meta(soup, "meta[property='og:title']"),
|
| 1412 |
+
"description": self.meta(soup, "meta[property='og:description']"),
|
| 1413 |
+
"image": self.meta(soup, "meta[property='og:image']"),
|
| 1414 |
+
"url": self.abs_url(self.meta(soup, "meta[property='og:url']")),
|
| 1415 |
+
"type": self.meta(soup, "meta[property='og:type']"),
|
| 1416 |
+
"site_name": self.meta(soup, "meta[property='og:site_name']"),
|
| 1417 |
+
},
|
| 1418 |
+
"twitter": {
|
| 1419 |
+
"card": self.meta(soup, "meta[name='twitter:card']"),
|
| 1420 |
+
"title": self.meta(soup, "meta[name='twitter:title']"),
|
| 1421 |
+
"description": self.meta(soup, "meta[name='twitter:description']"),
|
| 1422 |
+
"image": self.meta(soup, "meta[name='twitter:image']"),
|
| 1423 |
+
},
|
| 1424 |
+
}
|
| 1425 |
+
|
| 1426 |
+
def extract_json_ld(self, soup: BeautifulSoup) -> list[Any]:
|
| 1427 |
+
"""Extract JSON-LD structured data."""
|
| 1428 |
+
|
| 1429 |
+
output = []
|
| 1430 |
+
for script in soup.select("script[type='application/ld+json']"):
|
| 1431 |
+
raw = script.string or script.get_text(strip=True)
|
| 1432 |
+
if not raw:
|
| 1433 |
+
continue
|
| 1434 |
+
try:
|
| 1435 |
+
output.append(json.loads(raw))
|
| 1436 |
+
except Exception:
|
| 1437 |
+
output.append({"raw": raw})
|
| 1438 |
+
return output
|
| 1439 |
+
|
| 1440 |
+
def extract_pagination(self, soup: BeautifulSoup) -> dict[str, Any]:
|
| 1441 |
+
"""Extract pagination links."""
|
| 1442 |
+
|
| 1443 |
+
links = []
|
| 1444 |
+
for a in soup.select(".pagination a[href], a[rel='next'], a[rel='prev'], a[href*='page=']"):
|
| 1445 |
+
links.append(
|
| 1446 |
+
{
|
| 1447 |
+
"label": self.text(a),
|
| 1448 |
+
"url": self.abs_url(self.attr(a, "href")),
|
| 1449 |
+
"path": self.attr(a, "href"),
|
| 1450 |
+
"rel": self.attr(a, "rel"),
|
| 1451 |
+
}
|
| 1452 |
+
)
|
| 1453 |
+
return {"links": self.dedupe_by(links, "url")}
|
| 1454 |
+
|
| 1455 |
+
# ======================================================================
|
| 1456 |
+
# Tiny utilities
|
| 1457 |
+
# ======================================================================
|
| 1458 |
+
|
| 1459 |
+
def link_item(self, a: Optional[Tag]) -> Optional[dict[str, Any]]:
|
| 1460 |
+
"""Convert an anchor tag into label/url/path dict."""
|
| 1461 |
+
|
| 1462 |
+
if not a:
|
| 1463 |
+
return None
|
| 1464 |
+
href = self.attr(a, "href")
|
| 1465 |
+
label = self.text(a)
|
| 1466 |
+
if not href or not label:
|
| 1467 |
+
return None
|
| 1468 |
+
return {"label": label, "url": self.abs_url(href), "path": href}
|
| 1469 |
+
|
| 1470 |
+
def text(self, node: Optional[Tag]) -> Optional[str]:
|
| 1471 |
+
"""Get normalized visible text."""
|
| 1472 |
+
|
| 1473 |
+
if not node:
|
| 1474 |
+
return None
|
| 1475 |
+
value = node.get_text(" ", strip=True)
|
| 1476 |
+
value = html.unescape(value)
|
| 1477 |
+
value = re.sub(r"\s+", " ", value).strip()
|
| 1478 |
+
return value or None
|
| 1479 |
+
|
| 1480 |
+
def attr(self, node: Optional[Tag], name: str) -> Optional[str]:
|
| 1481 |
+
"""Get normalized attribute value."""
|
| 1482 |
+
|
| 1483 |
+
if not node:
|
| 1484 |
+
return None
|
| 1485 |
+
value = node.get(name)
|
| 1486 |
+
if value is None:
|
| 1487 |
+
return None
|
| 1488 |
+
if isinstance(value, list):
|
| 1489 |
+
value = " ".join(str(x) for x in value)
|
| 1490 |
+
value = html.unescape(str(value)).strip()
|
| 1491 |
+
return value or None
|
| 1492 |
+
|
| 1493 |
+
def meta(self, soup: BeautifulSoup, selector: str) -> Optional[str]:
|
| 1494 |
+
"""Get meta content."""
|
| 1495 |
+
|
| 1496 |
+
return self.attr(soup.select_one(selector), "content")
|
| 1497 |
+
|
| 1498 |
+
def extract_background_image(self, node: Optional[Tag]) -> Optional[str]:
|
| 1499 |
+
"""Extract CSS background image URL."""
|
| 1500 |
+
|
| 1501 |
+
style = self.attr(node, "style")
|
| 1502 |
+
if not style:
|
| 1503 |
+
return None
|
| 1504 |
+
match = re.search(r"url\((['\"]?)(.*?)\1\)", style)
|
| 1505 |
+
return self.abs_url(match.group(2)) if match else None
|
| 1506 |
+
|
| 1507 |
+
def clean_movie_title_from_page(self, title: Optional[str]) -> Optional[str]:
|
| 1508 |
+
"""Clean movie title from SEO page title."""
|
| 1509 |
+
|
| 1510 |
+
if not title:
|
| 1511 |
+
return None
|
| 1512 |
+
title = re.sub(r"^Watch\s+", "", title, flags=re.I)
|
| 1513 |
+
title = re.sub(r"\s+Online\s+Free.*$", "", title, flags=re.I)
|
| 1514 |
+
return title.strip() or None
|
| 1515 |
+
|
| 1516 |
+
def clean_tv_title_from_page(self, title: Optional[str]) -> Optional[str]:
|
| 1517 |
+
"""Clean TV show title from SEO page title."""
|
| 1518 |
+
|
| 1519 |
+
if not title:
|
| 1520 |
+
return None
|
| 1521 |
+
title = re.sub(r"^Watch\s+", "", title, flags=re.I)
|
| 1522 |
+
title = re.sub(r"\s+Online\s+Free.*$", "", title, flags=re.I)
|
| 1523 |
+
title = re.sub(r"\s+\|\s+StreamIMDB.*$", "", title, flags=re.I)
|
| 1524 |
+
return title.strip() or None
|
| 1525 |
+
|
| 1526 |
+
def clean_episode_title(self, title: Optional[str]) -> Optional[str]:
|
| 1527 |
+
"""Remove SxxExx prefix if present."""
|
| 1528 |
+
|
| 1529 |
+
if not title:
|
| 1530 |
+
return None
|
| 1531 |
+
title = re.sub(r"\bS\d{1,2}E\d{1,2}\b\s*[—:-]?\s*", "", title).strip()
|
| 1532 |
+
return title or None
|
| 1533 |
+
|
| 1534 |
+
def clean_section_title(self, title: str) -> str:
|
| 1535 |
+
"""Clean section title."""
|
| 1536 |
+
|
| 1537 |
+
title = re.sub(r"^\s*[|/\\\-–—]+\s*", "", title or "")
|
| 1538 |
+
title = title.replace("·", " ")
|
| 1539 |
+
title = re.sub(r"\s+", " ", title).strip()
|
| 1540 |
+
return title
|
| 1541 |
+
|
| 1542 |
+
def detect_type(self, href: Optional[str], hint: Optional[str] = None) -> Optional[str]:
|
| 1543 |
+
"""Detect movie/tv using href and visible badge/meta text."""
|
| 1544 |
+
|
| 1545 |
+
blob = f"{href or ''} {hint or ''}".lower()
|
| 1546 |
+
if "/movie/" in blob or "movie" in blob:
|
| 1547 |
+
return "movie"
|
| 1548 |
+
if "/tv/" in blob or "tv" in blob or "series" in blob:
|
| 1549 |
+
return "tv"
|
| 1550 |
+
return None
|
| 1551 |
+
|
| 1552 |
+
def guess_year(self, text_value: str) -> Optional[int]:
|
| 1553 |
+
"""Guess year from text."""
|
| 1554 |
+
|
| 1555 |
+
match = re.search(r"\b(19\d{2}|20\d{2})\b", text_value or "")
|
| 1556 |
+
return int(match.group(1)) if match else None
|
| 1557 |
+
|
| 1558 |
+
def guess_date(self, text_value: str) -> Optional[str]:
|
| 1559 |
+
"""Guess YYYY-MM-DD from text."""
|
| 1560 |
+
|
| 1561 |
+
match = re.search(r"\b(19\d{2}|20\d{2})-\d{2}-\d{2}\b", text_value or "")
|
| 1562 |
+
return match.group(0) if match else None
|
| 1563 |
+
|
| 1564 |
+
def guess_rating(self, values: list[Optional[str]]) -> Optional[float]:
|
| 1565 |
+
"""Guess 0-10 rating from text list."""
|
| 1566 |
+
|
| 1567 |
+
for value in values:
|
| 1568 |
+
if not value:
|
| 1569 |
+
continue
|
| 1570 |
+
match = re.search(r"\b([0-9](?:\.[0-9])?|10(?:\.0)?)\b", value)
|
| 1571 |
+
if match:
|
| 1572 |
+
num = float(match.group(1))
|
| 1573 |
+
if 0 <= num <= 10:
|
| 1574 |
+
return num
|
| 1575 |
+
return None
|
| 1576 |
+
|
| 1577 |
+
def guess_runtime(self, parts: list[Optional[str]]) -> Optional[str]:
|
| 1578 |
+
"""Guess runtime like 2h 23m."""
|
| 1579 |
+
|
| 1580 |
+
for part in parts:
|
| 1581 |
+
if part and re.search(r"\b\d+h(?:\s*\d+m)?\b|\b\d+m\b", part):
|
| 1582 |
+
return part
|
| 1583 |
+
return None
|
| 1584 |
+
|
| 1585 |
+
def guess_genres(self, parts: list[Optional[str]]) -> list[str]:
|
| 1586 |
+
"""Guess genre labels from meta parts."""
|
| 1587 |
+
|
| 1588 |
+
genres = []
|
| 1589 |
+
for part in parts:
|
| 1590 |
+
if not part:
|
| 1591 |
+
continue
|
| 1592 |
+
if re.fullmatch(r"(19\d{2}|20\d{2})", part):
|
| 1593 |
+
continue
|
| 1594 |
+
if re.search(r"\b\d+h(?:\s*\d+m)?\b|\b\d+m\b", part):
|
| 1595 |
+
continue
|
| 1596 |
+
if re.fullmatch(r"[0-9](?:\.[0-9])?|10(?:\.0)?", part):
|
| 1597 |
+
continue
|
| 1598 |
+
if len(part) <= 40:
|
| 1599 |
+
genres.append(part)
|
| 1600 |
+
return genres
|
| 1601 |
+
|
| 1602 |
+
def extract_episode_code(self, text_value: str) -> Optional[str]:
|
| 1603 |
+
"""Extract SxxExx code."""
|
| 1604 |
+
|
| 1605 |
+
match = re.search(r"\bS\d{1,2}E\d{1,2}\b", text_value or "", flags=re.I)
|
| 1606 |
+
return match.group(0).upper() if match else None
|
| 1607 |
+
|
| 1608 |
+
def extract_show_title_from_episode_title(self, title: Optional[str]) -> Optional[str]:
|
| 1609 |
+
"""Extract show title from title like 'Watch Lucifer S1E3 | StreamIMDB'."""
|
| 1610 |
+
|
| 1611 |
+
if not title:
|
| 1612 |
+
return None
|
| 1613 |
+
title = re.sub(r"^Watch\s+", "", title, flags=re.I)
|
| 1614 |
+
title = re.sub(r"\s+S\d{1,2}E\d{1,2}.*$", "", title, flags=re.I)
|
| 1615 |
+
return title.strip() or None
|
| 1616 |
+
|
| 1617 |
+
def extract_air_date(self, soup: BeautifulSoup) -> Optional[str]:
|
| 1618 |
+
"""Extract episode air date."""
|
| 1619 |
+
|
| 1620 |
+
meta_text = " ".join(self.text(x) or "" for x in soup.select(".cb-detail-meta, .cb-detail-meta-item, time"))
|
| 1621 |
+
return self.guess_date(meta_text)
|
| 1622 |
+
|
| 1623 |
+
def parse_episode_numbers_from_url(self, url_or_path: str) -> dict[str, Optional[int]]:
|
| 1624 |
+
"""Parse /season/<n>/episode/<n> numbers."""
|
| 1625 |
+
|
| 1626 |
+
season = episode = None
|
| 1627 |
+
m = re.search(r"/season/(\d+)", url_or_path or "")
|
| 1628 |
+
if m:
|
| 1629 |
+
season = int(m.group(1))
|
| 1630 |
+
m = re.search(r"/episode/(\d+)", url_or_path or "")
|
| 1631 |
+
if m:
|
| 1632 |
+
episode = int(m.group(1))
|
| 1633 |
+
return {"season": season, "episode": episode}
|
| 1634 |
+
|
| 1635 |
+
def safe_int(self, value: Optional[str]) -> Optional[int]:
|
| 1636 |
+
"""Extract first int from string."""
|
| 1637 |
+
|
| 1638 |
+
if not value:
|
| 1639 |
+
return None
|
| 1640 |
+
match = re.search(r"\d+", value)
|
| 1641 |
+
return int(match.group(0)) if match else None
|
| 1642 |
+
|
| 1643 |
+
def looks_like_media(self, value: str) -> bool:
|
| 1644 |
+
"""Check direct media file extension."""
|
| 1645 |
+
|
| 1646 |
+
clean = value.lower().split("?", 1)[0].split("#", 1)[0]
|
| 1647 |
+
return clean.endswith(MEDIA_EXTENSIONS)
|
| 1648 |
+
|
| 1649 |
+
def find_literal_media_urls(self, raw: str) -> list[str]:
|
| 1650 |
+
"""Find literal direct media URLs in raw HTML/JS."""
|
| 1651 |
+
|
| 1652 |
+
absolute_pattern = r"https?://[^\s'\"<>]+?(?:\.mp4|\.webm|\.ogg|\.m3u8|\.mpd|\.mov|\.m4v)(?:\?[^\s'\"<>]*)?"
|
| 1653 |
+
relative_pattern = r"(/[A-Za-z0-9_\-./%]+?(?:\.mp4|\.webm|\.ogg|\.m3u8|\.mpd|\.mov|\.m4v)(?:\?[^\s'\"<>]*)?)"
|
| 1654 |
+
found = re.findall(absolute_pattern, raw, flags=re.I)
|
| 1655 |
+
found.extend(re.findall(relative_pattern, raw, flags=re.I))
|
| 1656 |
+
return self.dedupe_values(found)
|
| 1657 |
+
|
| 1658 |
+
def dedupe_values(self, values: list[Any]) -> list[Any]:
|
| 1659 |
+
"""Deduplicate primitive values/dicts preserving order."""
|
| 1660 |
+
|
| 1661 |
+
output = []
|
| 1662 |
+
seen = set()
|
| 1663 |
+
for value in values:
|
| 1664 |
+
if not value:
|
| 1665 |
+
continue
|
| 1666 |
+
key = json.dumps(value, ensure_ascii=False, sort_keys=True) if isinstance(value, dict) else str(value)
|
| 1667 |
+
if key in seen:
|
| 1668 |
+
continue
|
| 1669 |
+
output.append(value)
|
| 1670 |
+
seen.add(key)
|
| 1671 |
+
return output
|
| 1672 |
+
|
| 1673 |
+
def dedupe_by(self, items: list[dict[str, Any]], key: str) -> list[dict[str, Any]]:
|
| 1674 |
+
"""Deduplicate dict list by key."""
|
| 1675 |
+
|
| 1676 |
+
output = []
|
| 1677 |
+
seen = set()
|
| 1678 |
+
for item in items:
|
| 1679 |
+
value = item.get(key)
|
| 1680 |
+
if not value:
|
| 1681 |
+
output.append(item)
|
| 1682 |
+
continue
|
| 1683 |
+
if value in seen:
|
| 1684 |
+
continue
|
| 1685 |
+
output.append(item)
|
| 1686 |
+
seen.add(value)
|
| 1687 |
+
return output
|
| 1688 |
+
|
| 1689 |
+
|
| 1690 |
+
# =============================================================================
|
| 1691 |
+
# CLI
|
| 1692 |
+
# =============================================================================
|
| 1693 |
+
|
| 1694 |
+
|
| 1695 |
+
def read_optional_file(path: Optional[str]) -> Optional[str]:
|
| 1696 |
+
"""Read local HTML file for --from-file testing."""
|
| 1697 |
+
|
| 1698 |
+
if not path:
|
| 1699 |
+
return None
|
| 1700 |
+
with open(path, "r", encoding="utf-8", errors="ignore") as f:
|
| 1701 |
+
return f.read()
|
| 1702 |
+
|
| 1703 |
+
|
| 1704 |
+
def build_parser() -> argparse.ArgumentParser:
|
| 1705 |
+
"""Create CLI parser."""
|
| 1706 |
+
|
| 1707 |
+
parser = argparse.ArgumentParser(description="CraftMovies metadata extractor")
|
| 1708 |
+
parser.add_argument("--base-url", default="https://streamimdb.ru")
|
| 1709 |
+
parser.add_argument("--timeout", type=int, default=10)
|
| 1710 |
+
parser.add_argument("--debug", action="store_true")
|
| 1711 |
+
parser.add_argument("--pretty", action="store_true")
|
| 1712 |
+
parser.add_argument("--save", default=None, help="Save JSON to file")
|
| 1713 |
+
parser.add_argument("--from-file", default=None, help="Use saved HTML instead of fetching URL")
|
| 1714 |
+
|
| 1715 |
+
sub = parser.add_subparsers(dest="command", required=True)
|
| 1716 |
+
|
| 1717 |
+
sub.add_parser("home", help="Extract home page")
|
| 1718 |
+
|
| 1719 |
+
s = sub.add_parser("search", help="Search only")
|
| 1720 |
+
s.add_argument("query")
|
| 1721 |
+
|
| 1722 |
+
sa = sub.add_parser("search-all", help="Search + expand TV seasons/episodes/episode embed URLs")
|
| 1723 |
+
sa.add_argument("query")
|
| 1724 |
+
sa.add_argument("--no-episode-details", action="store_true", help="Only parse TV show pages, do not fetch episode pages")
|
| 1725 |
+
sa.add_argument("--limit-tv", type=int, default=0, help="Limit TV shows expanded")
|
| 1726 |
+
sa.add_argument("--limit-episodes", type=int, default=0, help="Limit episode pages fetched per TV show")
|
| 1727 |
+
|
| 1728 |
+
fm = sub.add_parser("fetch-movies", help="Fetch /browse/movie latest/trendy movie rows")
|
| 1729 |
+
fm.add_argument("--details", action="store_true", help="Fetch each movie detail page too")
|
| 1730 |
+
fm.add_argument("--limit-items", type=int, default=0, help="Limit detail pages fetched")
|
| 1731 |
+
|
| 1732 |
+
br = sub.add_parser("browse", help="Generic browse extractor")
|
| 1733 |
+
br.add_argument("media_type", choices=["movie", "tv"])
|
| 1734 |
+
br.add_argument("--details", action="store_true", help="Fetch item detail pages too")
|
| 1735 |
+
br.add_argument("--episode-details", action="store_true", help="For TV browse, fetch episode pages too")
|
| 1736 |
+
br.add_argument("--limit-items", type=int, default=0)
|
| 1737 |
+
br.add_argument("--limit-episodes", type=int, default=0)
|
| 1738 |
+
|
| 1739 |
+
m = sub.add_parser("movie", help="Extract movie detail page")
|
| 1740 |
+
m.add_argument("url_or_path")
|
| 1741 |
+
|
| 1742 |
+
tv = sub.add_parser("tv", help="Extract TV show page")
|
| 1743 |
+
tv.add_argument("url_or_path")
|
| 1744 |
+
tv.add_argument("--no-full", action="store_true", help="Do not fetch episode pages")
|
| 1745 |
+
tv.add_argument("--limit-episodes", type=int, default=0)
|
| 1746 |
+
|
| 1747 |
+
ep = sub.add_parser("episode", help="Extract episode detail page")
|
| 1748 |
+
ep.add_argument("url_or_path")
|
| 1749 |
+
|
| 1750 |
+
return parser
|
| 1751 |
+
|
| 1752 |
+
|
| 1753 |
+
def main() -> int:
|
| 1754 |
+
"""CLI entry point."""
|
| 1755 |
+
|
| 1756 |
+
args = build_parser().parse_args()
|
| 1757 |
+
cm = CraftMovies(
|
| 1758 |
+
CraftMoviesConfig(
|
| 1759 |
+
base_url=args.base_url,
|
| 1760 |
+
timeout=args.timeout,
|
| 1761 |
+
debug=args.debug,
|
| 1762 |
+
)
|
| 1763 |
+
)
|
| 1764 |
+
|
| 1765 |
+
html_text = read_optional_file(args.from_file)
|
| 1766 |
+
|
| 1767 |
+
try:
|
| 1768 |
+
if args.command == "home":
|
| 1769 |
+
data = cm.home(html_text=html_text)
|
| 1770 |
+
|
| 1771 |
+
elif args.command == "search":
|
| 1772 |
+
data = cm.search(args.query, html_text=html_text)
|
| 1773 |
+
|
| 1774 |
+
elif args.command == "search-all":
|
| 1775 |
+
data = cm.searchAll(
|
| 1776 |
+
args.query,
|
| 1777 |
+
include_episode_details=not args.no_episode_details,
|
| 1778 |
+
limit_tv=args.limit_tv,
|
| 1779 |
+
limit_episodes=args.limit_episodes,
|
| 1780 |
+
)
|
| 1781 |
+
|
| 1782 |
+
elif args.command == "fetch-movies":
|
| 1783 |
+
data = cm.fetchMovies(include_details=args.details, limit_items=args.limit_items)
|
| 1784 |
+
if html_text is not None:
|
| 1785 |
+
data = cm.browse("movie", include_details=args.details, limit_items=args.limit_items, html_text=html_text)
|
| 1786 |
+
|
| 1787 |
+
elif args.command == "browse":
|
| 1788 |
+
data = cm.browse(
|
| 1789 |
+
args.media_type,
|
| 1790 |
+
include_details=args.details,
|
| 1791 |
+
include_episode_details=args.episode_details,
|
| 1792 |
+
limit_items=args.limit_items,
|
| 1793 |
+
limit_episodes=args.limit_episodes,
|
| 1794 |
+
html_text=html_text,
|
| 1795 |
+
)
|
| 1796 |
+
|
| 1797 |
+
elif args.command == "movie":
|
| 1798 |
+
data = cm.movie(args.url_or_path, html_text=html_text)
|
| 1799 |
+
|
| 1800 |
+
elif args.command == "tv":
|
| 1801 |
+
data = cm.tvShow(
|
| 1802 |
+
args.url_or_path,
|
| 1803 |
+
full=not args.no_full,
|
| 1804 |
+
limit_episodes=args.limit_episodes,
|
| 1805 |
+
html_text=html_text,
|
| 1806 |
+
)
|
| 1807 |
+
|
| 1808 |
+
elif args.command == "episode":
|
| 1809 |
+
data = cm.episode(args.url_or_path, html_text=html_text)
|
| 1810 |
+
|
| 1811 |
+
else:
|
| 1812 |
+
raise ValueError("Unknown command")
|
| 1813 |
+
|
| 1814 |
+
json_text = json.dumps(data, ensure_ascii=False, indent=2 if args.pretty else None)
|
| 1815 |
+
|
| 1816 |
+
if args.save:
|
| 1817 |
+
with open(args.save, "w", encoding="utf-8") as f:
|
| 1818 |
+
f.write(json_text)
|
| 1819 |
+
if args.debug:
|
| 1820 |
+
print(f"[debug] Saved to {args.save}", file=sys.stderr, flush=True)
|
| 1821 |
+
|
| 1822 |
+
print(json_text)
|
| 1823 |
+
return 0
|
| 1824 |
+
|
| 1825 |
+
except requests.HTTPError as exc:
|
| 1826 |
+
print(json.dumps({"error": "HTTP error", "details": str(exc)}, indent=2))
|
| 1827 |
+
return 2
|
| 1828 |
+
except requests.RequestException as exc:
|
| 1829 |
+
print(json.dumps({"error": "Request error", "details": str(exc)}, indent=2))
|
| 1830 |
+
return 3
|
| 1831 |
+
except Exception as exc:
|
| 1832 |
+
print(json.dumps({"error": "Runtime error", "details": str(exc)}, indent=2))
|
| 1833 |
+
return 1
|
| 1834 |
+
|
| 1835 |
+
|
| 1836 |
+
if __name__ == "__main__":
|
| 1837 |
+
raise SystemExit(main())
|
main.py
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
CraftMovies Hugging Face Space API
|
| 3 |
+
==================================
|
| 4 |
+
|
| 5 |
+
FastAPI backend for CraftMovies, ready for Hugging Face Spaces Docker hosting.
|
| 6 |
+
|
| 7 |
+
Default port:
|
| 8 |
+
7860
|
| 9 |
+
|
| 10 |
+
Local run:
|
| 11 |
+
python -m uvicorn main:app --host 0.0.0.0 --port 7860
|
| 12 |
+
|
| 13 |
+
Endpoints:
|
| 14 |
+
GET /
|
| 15 |
+
GET /health
|
| 16 |
+
GET /api/home
|
| 17 |
+
GET /api/search?q=lucifer
|
| 18 |
+
GET /api/search-all?q=lucifer&limit_tv=1&limit_episodes=5
|
| 19 |
+
GET /api/fetch-movies
|
| 20 |
+
GET /api/fetch-tv
|
| 21 |
+
GET /api/browse/movie
|
| 22 |
+
GET /api/browse/tv
|
| 23 |
+
GET /api/movie?url=/movie/5nspt-the-avengers-2012
|
| 24 |
+
GET /api/tv-show?url=/tv/56tj4-lucifer&limit_episodes=5
|
| 25 |
+
GET /api/episode?url=/tv/56tj4-lucifer/season/1/episode/3
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
from __future__ import annotations
|
| 29 |
+
|
| 30 |
+
import hashlib
|
| 31 |
+
import json
|
| 32 |
+
import os
|
| 33 |
+
import time
|
| 34 |
+
from typing import Any, Callable, Optional
|
| 35 |
+
|
| 36 |
+
from fastapi import FastAPI, HTTPException, Query, Request
|
| 37 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 38 |
+
from fastapi.responses import JSONResponse, RedirectResponse
|
| 39 |
+
|
| 40 |
+
from craftmovies import CraftMovies, CraftMoviesConfig
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class Settings:
|
| 44 |
+
"""Environment settings for Hugging Face Space deployment."""
|
| 45 |
+
|
| 46 |
+
BASE_URL: str = os.getenv("CRAFTMOVIES_BASE_URL", "https://streamimdb.ru")
|
| 47 |
+
REQUEST_TIMEOUT: int = int(os.getenv("CRAFTMOVIES_TIMEOUT", "15"))
|
| 48 |
+
DEBUG: bool = os.getenv("CRAFTMOVIES_DEBUG", "false").lower() == "true"
|
| 49 |
+
CACHE_TTL_SECONDS: int = int(os.getenv("CRAFTMOVIES_CACHE_TTL_SECONDS", "300"))
|
| 50 |
+
CORS_ORIGINS: list[str] = [
|
| 51 |
+
origin.strip()
|
| 52 |
+
for origin in os.getenv("CRAFTMOVIES_CORS_ORIGINS", "*").split(",")
|
| 53 |
+
if origin.strip()
|
| 54 |
+
]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
settings = Settings()
|
| 58 |
+
|
| 59 |
+
app = FastAPI(
|
| 60 |
+
title="CraftMovies API",
|
| 61 |
+
description=(
|
| 62 |
+
"Hugging Face Spaces-ready API for CraftMovies. "
|
| 63 |
+
"Returns metadata, seasons, episodes, posters, recommendations, and visible iframe embed URLs."
|
| 64 |
+
),
|
| 65 |
+
version="1.0.0",
|
| 66 |
+
docs_url="/docs",
|
| 67 |
+
redoc_url="/redoc",
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
app.add_middleware(
|
| 71 |
+
CORSMiddleware,
|
| 72 |
+
allow_origins=settings.CORS_ORIGINS,
|
| 73 |
+
allow_credentials=True,
|
| 74 |
+
allow_methods=["GET", "DELETE"],
|
| 75 |
+
allow_headers=["*"],
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
cm = CraftMovies(
|
| 79 |
+
CraftMoviesConfig(
|
| 80 |
+
base_url=settings.BASE_URL,
|
| 81 |
+
timeout=settings.REQUEST_TIMEOUT,
|
| 82 |
+
debug=settings.DEBUG,
|
| 83 |
+
)
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
_CACHE: dict[str, dict[str, Any]] = {}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def make_cache_key(name: str, params: dict[str, Any]) -> str:
|
| 90 |
+
payload = json.dumps({"name": name, "params": params}, sort_keys=True, ensure_ascii=False)
|
| 91 |
+
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def get_cached(key: str) -> Optional[Any]:
|
| 95 |
+
item = _CACHE.get(key)
|
| 96 |
+
if not item:
|
| 97 |
+
return None
|
| 98 |
+
|
| 99 |
+
age = time.time() - item["created_at"]
|
| 100 |
+
if age > settings.CACHE_TTL_SECONDS:
|
| 101 |
+
_CACHE.pop(key, None)
|
| 102 |
+
return None
|
| 103 |
+
|
| 104 |
+
return item["value"]
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def set_cached(key: str, value: Any) -> None:
|
| 108 |
+
_CACHE[key] = {"created_at": time.time(), "value": value}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def cached_call(name: str, params: dict[str, Any], fn: Callable[[], Any], refresh: bool = False) -> Any:
|
| 112 |
+
key = make_cache_key(name, params)
|
| 113 |
+
|
| 114 |
+
if not refresh:
|
| 115 |
+
cached = get_cached(key)
|
| 116 |
+
if cached is not None:
|
| 117 |
+
if isinstance(cached, dict):
|
| 118 |
+
cached = dict(cached)
|
| 119 |
+
cached["_cache"] = "hit"
|
| 120 |
+
return cached
|
| 121 |
+
|
| 122 |
+
value = fn()
|
| 123 |
+
if isinstance(value, dict):
|
| 124 |
+
value["_cache"] = "miss"
|
| 125 |
+
set_cached(key, value)
|
| 126 |
+
return value
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def require_url(value: Optional[str]) -> str:
|
| 130 |
+
if not value or not value.strip():
|
| 131 |
+
raise HTTPException(status_code=400, detail="Missing required query parameter: url")
|
| 132 |
+
return value.strip()
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@app.exception_handler(Exception)
|
| 136 |
+
async def general_exception_handler(request: Request, exc: Exception):
|
| 137 |
+
return JSONResponse(
|
| 138 |
+
status_code=500,
|
| 139 |
+
content={
|
| 140 |
+
"error": "Internal server error",
|
| 141 |
+
"details": str(exc),
|
| 142 |
+
"path": str(request.url.path),
|
| 143 |
+
},
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@app.get("/", include_in_schema=False)
|
| 148 |
+
def root():
|
| 149 |
+
"""Redirect root to docs for easy Hugging Face Space testing."""
|
| 150 |
+
return RedirectResponse(url="/docs")
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@app.get("/health")
|
| 154 |
+
def health():
|
| 155 |
+
return {
|
| 156 |
+
"status": "ok",
|
| 157 |
+
"service": "CraftMovies API",
|
| 158 |
+
"environment": "huggingface-space",
|
| 159 |
+
"base_url": settings.BASE_URL,
|
| 160 |
+
"cache_ttl_seconds": settings.CACHE_TTL_SECONDS,
|
| 161 |
+
"docs": "/docs",
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@app.get("/api/cache/stats")
|
| 166 |
+
def cache_stats():
|
| 167 |
+
return {"items": len(_CACHE), "ttl_seconds": settings.CACHE_TTL_SECONDS}
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
@app.delete("/api/cache")
|
| 171 |
+
def clear_cache():
|
| 172 |
+
_CACHE.clear()
|
| 173 |
+
return {"status": "cleared"}
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
@app.get("/api/home")
|
| 177 |
+
def api_home(refresh: bool = Query(False)):
|
| 178 |
+
return cached_call(
|
| 179 |
+
"home",
|
| 180 |
+
{"base_url": settings.BASE_URL},
|
| 181 |
+
lambda: cm.home(),
|
| 182 |
+
refresh=refresh,
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
@app.get("/api/search")
|
| 187 |
+
def api_search(
|
| 188 |
+
q: str = Query(..., min_length=1, description="Search query"),
|
| 189 |
+
refresh: bool = Query(False),
|
| 190 |
+
):
|
| 191 |
+
return cached_call(
|
| 192 |
+
"search",
|
| 193 |
+
{"q": q, "base_url": settings.BASE_URL},
|
| 194 |
+
lambda: cm.search(q),
|
| 195 |
+
refresh=refresh,
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
@app.get("/api/search-all")
|
| 200 |
+
def api_search_all(
|
| 201 |
+
q: str = Query(..., min_length=1, description="Search query"),
|
| 202 |
+
include_episode_details: bool = Query(True, description="Fetch episode pages for TV results"),
|
| 203 |
+
limit_tv: int = Query(0, ge=0, description="Max TV shows to expand. 0 means all."),
|
| 204 |
+
limit_episodes: int = Query(0, ge=0, description="Max episode pages per show. 0 means all."),
|
| 205 |
+
refresh: bool = Query(False),
|
| 206 |
+
):
|
| 207 |
+
return cached_call(
|
| 208 |
+
"search_all",
|
| 209 |
+
{
|
| 210 |
+
"q": q,
|
| 211 |
+
"include_episode_details": include_episode_details,
|
| 212 |
+
"limit_tv": limit_tv,
|
| 213 |
+
"limit_episodes": limit_episodes,
|
| 214 |
+
"base_url": settings.BASE_URL,
|
| 215 |
+
},
|
| 216 |
+
lambda: cm.searchAll(
|
| 217 |
+
q,
|
| 218 |
+
include_episode_details=include_episode_details,
|
| 219 |
+
limit_tv=limit_tv,
|
| 220 |
+
limit_episodes=limit_episodes,
|
| 221 |
+
),
|
| 222 |
+
refresh=refresh,
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@app.get("/api/fetch-movies")
|
| 227 |
+
def api_fetch_movies(
|
| 228 |
+
include_details: bool = Query(False),
|
| 229 |
+
limit_items: int = Query(0, ge=0),
|
| 230 |
+
refresh: bool = Query(False),
|
| 231 |
+
):
|
| 232 |
+
return cached_call(
|
| 233 |
+
"fetch_movies",
|
| 234 |
+
{
|
| 235 |
+
"include_details": include_details,
|
| 236 |
+
"limit_items": limit_items,
|
| 237 |
+
"base_url": settings.BASE_URL,
|
| 238 |
+
},
|
| 239 |
+
lambda: cm.fetchMovies(include_details=include_details, limit_items=limit_items),
|
| 240 |
+
refresh=refresh,
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
@app.get("/api/fetch-tv")
|
| 245 |
+
def api_fetch_tv(
|
| 246 |
+
include_details: bool = Query(False),
|
| 247 |
+
include_episode_details: bool = Query(False),
|
| 248 |
+
limit_items: int = Query(0, ge=0),
|
| 249 |
+
limit_episodes: int = Query(0, ge=0),
|
| 250 |
+
refresh: bool = Query(False),
|
| 251 |
+
):
|
| 252 |
+
return cached_call(
|
| 253 |
+
"fetch_tv",
|
| 254 |
+
{
|
| 255 |
+
"include_details": include_details,
|
| 256 |
+
"include_episode_details": include_episode_details,
|
| 257 |
+
"limit_items": limit_items,
|
| 258 |
+
"limit_episodes": limit_episodes,
|
| 259 |
+
"base_url": settings.BASE_URL,
|
| 260 |
+
},
|
| 261 |
+
lambda: cm.fetchTV(
|
| 262 |
+
include_details=include_details,
|
| 263 |
+
include_episode_details=include_episode_details,
|
| 264 |
+
limit_items=limit_items,
|
| 265 |
+
limit_episodes=limit_episodes,
|
| 266 |
+
),
|
| 267 |
+
refresh=refresh,
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
@app.get("/api/browse/{media_type}")
|
| 272 |
+
def api_browse(
|
| 273 |
+
media_type: str,
|
| 274 |
+
include_details: bool = Query(False),
|
| 275 |
+
include_episode_details: bool = Query(False),
|
| 276 |
+
limit_items: int = Query(0, ge=0),
|
| 277 |
+
limit_episodes: int = Query(0, ge=0),
|
| 278 |
+
refresh: bool = Query(False),
|
| 279 |
+
):
|
| 280 |
+
if media_type not in {"movie", "tv"}:
|
| 281 |
+
raise HTTPException(status_code=400, detail="media_type must be 'movie' or 'tv'")
|
| 282 |
+
|
| 283 |
+
return cached_call(
|
| 284 |
+
"browse",
|
| 285 |
+
{
|
| 286 |
+
"media_type": media_type,
|
| 287 |
+
"include_details": include_details,
|
| 288 |
+
"include_episode_details": include_episode_details,
|
| 289 |
+
"limit_items": limit_items,
|
| 290 |
+
"limit_episodes": limit_episodes,
|
| 291 |
+
"base_url": settings.BASE_URL,
|
| 292 |
+
},
|
| 293 |
+
lambda: cm.browse(
|
| 294 |
+
media_type,
|
| 295 |
+
include_details=include_details,
|
| 296 |
+
include_episode_details=include_episode_details,
|
| 297 |
+
limit_items=limit_items,
|
| 298 |
+
limit_episodes=limit_episodes,
|
| 299 |
+
),
|
| 300 |
+
refresh=refresh,
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
@app.get("/api/movie")
|
| 305 |
+
def api_movie(
|
| 306 |
+
url: str = Query(..., description="Movie URL/path"),
|
| 307 |
+
refresh: bool = Query(False),
|
| 308 |
+
):
|
| 309 |
+
target_url = require_url(url)
|
| 310 |
+
|
| 311 |
+
return cached_call(
|
| 312 |
+
"movie",
|
| 313 |
+
{"url": target_url, "base_url": settings.BASE_URL},
|
| 314 |
+
lambda: cm.movie(target_url),
|
| 315 |
+
refresh=refresh,
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
@app.get("/api/tv-show")
|
| 320 |
+
def api_tv_show(
|
| 321 |
+
url: str = Query(..., description="TV show URL/path"),
|
| 322 |
+
full: bool = Query(True, description="Fetch episode pages too"),
|
| 323 |
+
limit_episodes: int = Query(0, ge=0),
|
| 324 |
+
refresh: bool = Query(False),
|
| 325 |
+
):
|
| 326 |
+
target_url = require_url(url)
|
| 327 |
+
|
| 328 |
+
return cached_call(
|
| 329 |
+
"tv_show",
|
| 330 |
+
{
|
| 331 |
+
"url": target_url,
|
| 332 |
+
"full": full,
|
| 333 |
+
"limit_episodes": limit_episodes,
|
| 334 |
+
"base_url": settings.BASE_URL,
|
| 335 |
+
},
|
| 336 |
+
lambda: cm.tvShow(target_url, full=full, limit_episodes=limit_episodes),
|
| 337 |
+
refresh=refresh,
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
@app.get("/api/episode")
|
| 342 |
+
def api_episode(
|
| 343 |
+
url: str = Query(..., description="Episode URL/path"),
|
| 344 |
+
refresh: bool = Query(False),
|
| 345 |
+
):
|
| 346 |
+
target_url = require_url(url)
|
| 347 |
+
|
| 348 |
+
return cached_call(
|
| 349 |
+
"episode",
|
| 350 |
+
{"url": target_url, "base_url": settings.BASE_URL},
|
| 351 |
+
lambda: cm.episode(target_url),
|
| 352 |
+
refresh=refresh,
|
| 353 |
+
)
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi==0.115.6
|
| 2 |
+
uvicorn[standard]==0.34.0
|
| 3 |
+
requests==2.32.3
|
| 4 |
+
beautifulsoup4==4.12.3
|
| 5 |
+
python-dotenv==1.0.1
|
test_local.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
|
| 3 |
+
BASE = "http://127.0.0.1:7860"
|
| 4 |
+
|
| 5 |
+
print(requests.get(f"{BASE}/health").json())
|
| 6 |
+
print(requests.get(f"{BASE}/api/search", params={"q": "lucifer"}).json().keys())
|