Spaces:
Sleeping
Sleeping
Update app.py
Browse files123451 unmodified line7891011121314151617181920212223242526272829303132333435363738394024 unmodified lines65666768697071727314 unmodified lines88899091929394959697985 unmodified lines10410510610710810911010 unmodified lines12112212312412512612727 unmodified lines1551561571581591601611621631645 unmodified lines1701711721731741751761771785 unmodified lines18418518618718818919018 unmodified lines2092102112122132142152162172184 unmodified lines2232242252262272282296 unmodified lines236237238239240241242243import gradio as grimport requestsfrom bs4 import BeautifulSoupimport reimport time1 unmodified linefrom pathlib import Path# ββββββββββββββββββββββββββββββββββββββββββββββ# HTTP helpers# ββββββββββββββββββββββββββββββββββββββββββββββHEADERS = {"User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) ""AppleWebKit/537.36 (KHTML, like Gecko) ""Chrome/124.0.0.0 Safari/537.36"),"Accept-Language": "en-US,en;q=0.9","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Referer": "https://novelfire.net/",}SESSION = requests.Session()SESSION.headers.update(HEADERS)def fetch_html(url: str, retries: int = 3, timeout: int = 20) -> str:for attempt in range(1, retries + 1):try:resp = SESSION.get(url, timeout=timeout)resp.raise_for_status()return resp.textexcept requests.RequestException as exc:if attempt == retries:raise RuntimeError(f"Failed to fetch {url} after {retries} attempts: {exc}")time.sleep(2 ** attempt)# ββββββββββββββββββββββββββββββββββββββββββββββ24 unmodified linespage = 1while True:page_url = f"{chapters_base_url}?page={page}" if page > 1 else chapters_base_urlif log_fn:log_fn(f"π Fetching chapter list page {page}: {page_url}")html = fetch_html(page_url)soup = BeautifulSoup(html, "html.parser")14 unmodified linestitle_text = re.sub(r"^\d+\s*", "", title_text)title_text = re.sub(r"\d+\s*(second|minute|hour|day|week|month|year)s?\s*ago.*$","", title_text, flags=re.I).strip()all_chapters.append({"url": href, "title": title_text, "num": num})# Check for a next page linknext_page_exists = Falsefor pg_a in soup.select(".pagination a.page-link"):href_pg = pg_a.get("href", "")5 unmodified linesbreakpage += 1# Deduplicate & sortseen, unique = set(), []for ch in all_chapters:if ch["num"] not in seen:10 unmodified linesdef extract_chapter_content(html: str):soup = BeautifulSoup(html, "html.parser")title_tag = soup.select_one("span.chapter-title, h1.chapter-title, .chapter-title")title = title_tag.get_text(strip=True) if title_tag else ""content_div = soup.select_one("#content") or soup.select_one(27 unmodified lines# ββββββββββββββββββββββββββββββββββββββββββββββ# Scraper β generator so Gradio streams updates# ββββββββββββββββββββββββββββββββββββββββββββββ# HF Spaces: use /tmp for all I/O (writable, ephemeral)TMP_ROOT = Path("/tmp/novel_scraper")TMP_ROOT.mkdir(parents=True, exist_ok=True)5 unmodified lineslogs.append(msg)return "\n".join(logs[-80:])def emit(extra_log: str | None = None):if extra_log:log(extra_log)return "\n".join(logs[-80:]), gr.update(visible=False)try:5 unmodified lineschapters_base = base_chapters_url(url)yield emit(f"π Chapters base URL: {chapters_base}")# ββ 1. Collect all chapter links ββββββββββββββββββββββprogress(0.0, desc="Discovering chaptersβ¦")all_chapters = get_all_chapter_links(chapters_base, log_fn=log)yield emit()18 unmodified linesyield emit(f"π― Chapters {actual_start}β{actual_end} "f"({len(selected)} chapters) @ {rps} req/s")# ββ 3. Prepare cache folder βββββββββββββββββββββββββββsafe_novel = safe_filename(novel_title)html_folder = TMP_ROOT / safe_novel / "html_cache"html_folder.mkdir(parents=True, exist_ok=True)4 unmodified linestotal = len(selected)for idx, ch in enumerate(selected, start=1):progress(idx / total * 0.85, desc=f"Chapter {ch['num']} / {actual_end}β¦")html_path = html_folder / f"chapter_{ch['num']:05d}.html"if html_path.exists():6 unmodified linesyield emit(f" β [{idx}/{total}] Ch {ch['num']}: {ch['title']}")except RuntimeError as exc:yield emit(f" β [{idx}/{total}] Ch {ch['num']} FAILED: {exc}")compiled.append((ch["num"], ch["title"] or f"Chapter {ch['num']}",f"[Chapter {ch['num']} could not be downloaded.]"))time.sleep(delay)continue123451 unmodified line7891011121314151617181920212223242526272829303132333435363738394041424344454647484924 unmodified lines747576777879808182838414 unmodified lines991001011021031041051061071081095 unmodified lines11511611711811912010 unmodified lines13113213313413513613713813927 unmodified lines1671681691701711721731741755 unmodified lines1811821831841851861871881895 unmodified lines19519619719819920020118 unmodified lines2202212222232242252262272282294 unmodified lines2342352362372382392406 unmodified lines247248249250251252253254255256257import gradio as grimport cloudscraperfrom bs4 import BeautifulSoupimport reimport time1 unmodified linefrom pathlib import Path# ββββββββββββββββββββββββββββββββββββββββββββββ# HTTP β cloudscraper bypasses Cloudflare / 403# ββββββββββββββββββββββββββββββββββββββββββββββdef make_scraper():s = cloudscraper.create_scraper(browser={"browser": "chrome", "platform": "windows", "mobile": False})s.headers.update({"Accept-Language": "en-US,en;q=0.9","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8","Referer": "https://novelfire.net/","Cache-Control": "no-cache",})return sSCRAPER = make_scraper()def fetch_html(url: str, retries: int = 4, timeout: int = 30) -> str:global SCRAPERfor attempt in range(1, retries + 1):try:resp = SCRAPER.get(url, timeout=timeout)if resp.status_code == 403:# Recreate scraper with fresh fingerprint and retrySCRAPER = make_scraper()time.sleep(3 * attempt)continueresp.raise_for_status()return resp.textexcept Exception as exc:if attempt == retries:raise RuntimeError(f"Failed to fetch {url} after {retries} attempts: {exc}")time.sleep(2 ** attempt)raise RuntimeError(f"Failed to fetch {url} after {retries} attempts")# ββββββββββββββββββββββββββββββββββββββββββββββ24 unmodified linespage = 1while True:page_url = (f"{chapters_base_url}?page={page}" if page > 1 else chapters_base_url)if log_fn:log_fn(f"π Chapter list β page {page}: {page_url}")html = fetch_html(page_url)soup = BeautifulSoup(html, "html.parser")14 unmodified linestitle_text = re.sub(r"^\d+\s*", "", title_text)title_text = re.sub(r"\d+\s*(second|minute|hour|day|week|month|year)s?\s*ago.*$","", title_text, flags=re.I,).strip()all_chapters.append({"url": href, "title": title_text, "num": num})# Next page?next_page_exists = Falsefor pg_a in soup.select(".pagination a.page-link"):href_pg = pg_a.get("href", "")5 unmodified linesbreakpage += 1seen, unique = set(), []for ch in all_chapters:if ch["num"] not in seen:10 unmodified linesdef extract_chapter_content(html: str):soup = BeautifulSoup(html, "html.parser")title_tag = soup.select_one("span.chapter-title, h1.chapter-title, .chapter-title")title = title_tag.get_text(strip=True) if title_tag else ""content_div = soup.select_one("#content") or soup.select_one(27 unmodified lines# ββββββββββββββββββββββββββββββββββββββββββββββ# Scraper β streaming generator# ββββββββββββββββββββββββββββββββββββββββββββββTMP_ROOT = Path("/tmp/novel_scraper")TMP_ROOT.mkdir(parents=True, exist_ok=True)5 unmodified lineslogs.append(msg)return "\n".join(logs[-80:])def emit(msg: str | None = None):if msg:log(msg)return "\n".join(logs[-80:]), gr.update(visible=False)try:5 unmodified lineschapters_base = base_chapters_url(url)yield emit(f"π Chapters base URL: {chapters_base}")# ββ 1. Discover all chapters ββββββββββββββββββββββββββprogress(0.0, desc="Discovering chaptersβ¦")all_chapters = get_all_chapter_links(chapters_base, log_fn=log)yield emit()18 unmodified linesyield emit(f"π― Chapters {actual_start}β{actual_end} "f"({len(selected)} total) @ {rps} req/s")# ββ 3. Prepare cache ββββββββββββββββββββββββββββββββββsafe_novel = safe_filename(novel_title)html_folder = TMP_ROOT / safe_novel / "html_cache"html_folder.mkdir(parents=True, exist_ok=True)4 unmodified linestotal = len(selected)for idx, ch in enumerate(selected, start=1):progress(idx / total * 0.85, desc=f"Ch {ch['num']} / {actual_end}β¦")html_path = html_folder / f"chapter_{ch['num']:05d}.html"if html_path.exists():6 unmodified linesyield emit(f" β [{idx}/{total}] Ch {ch['num']}: {ch['title']}")except RuntimeError as exc:yield emit(f" β [{idx}/{total}] Ch {ch['num']} FAILED: {exc}")compiled.append((ch["num"],ch["title"] or f"Chapter {ch['num']}",f"[Chapter {ch['num']} could not be downloaded.]",))time.sleep(delay)continue
app.py+49-35