Neon-tech commited on
Commit
d3eee33
·
verified ·
1 Parent(s): acb52ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -66
app.py CHANGED
@@ -1,74 +1,100 @@
1
- from fastapi import FastAPI
2
- from fastapi.responses import FileResponse
3
- import os, requests, time, subprocess
 
4
  from bs4 import BeautifulSoup
5
- from PIL import Image
6
  from urllib.parse import quote
 
7
 
8
  app = FastAPI()
9
- BASE = "https://tcbscanmanga.com"
10
- OUT = "data"
11
- os.makedirs(OUT, exist_ok=True)
12
- headers = {'User-Agent': 'Mozilla/5.0'}
 
 
13
 
14
- @app.get("/search")
15
- def search(title: str):
16
- r = requests.get(f"{BASE}/search?search={quote(title)}", headers=headers)
17
- soup = BeautifulSoup(r.content, 'html.parser')
18
- results = []
19
- for item in soup.select('.c-tabs-item__content'):
20
- a = item.select_one('.post-title a')
21
- if not a: continue
22
- href = a.get('href', '')
23
- name = a.get_text(strip=True)
24
- slug = href.rstrip('/').split('/')[-1]
25
- chap = item.select_one('.chapter a')
26
- date = item.select_one('.post-on .font-meta')
27
- rating = item.select_one('.score')
28
- results.append({
29
- "title": name,
30
- "slug": slug,
31
- "latest": chap.get_text(strip=True) if chap else None,
32
- "date": date.get_text(strip=True) if date else None,
33
- "rating": rating.get_text(strip=True) if rating else None
34
- })
35
- return results
36
 
37
- @app.get("/pages/{slug}/{chapter}")
38
- def pages(slug: str, chapter: str):
39
- url = f"{BASE}/manga/{slug}/chapter-{chapter}"
40
- r = requests.get(url, headers=headers, timeout=10)
41
  r.raise_for_status()
42
- soup = BeautifulSoup(r.content, 'html.parser')
43
- imgs = soup.find_all('img', {'class': 'wp-manga-chapter-img'})
44
- links = []
45
- for img in imgs:
46
- src = img.get('src') or img.get('data-src')
47
- if not src: continue
48
- if not src.startswith('http'):
49
- src = BASE + src
50
- links.append(src)
51
- return {"slug": slug, "chapter": chapter, "pages": links}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
- @app.get("/download/{slug}/{chapter}")
54
- def download(slug: str, chapter: str):
55
- data = pages(slug, chapter)
56
- if not data["pages"]:
57
- return {"error": "no images"}
58
- ch_dir = f"{OUT}/{slug}/ch{chapter}"
59
- os.makedirs(ch_dir, exist_ok=True)
60
- paths = []
61
- for i, src in enumerate(data["pages"], 1):
62
- ir = requests.get(src, headers=headers, timeout=10)
63
- p = f"{ch_dir}/{i:03d}.png"
64
- open(p, 'wb').write(ir.content)
65
- paths.append(p)
66
- time.sleep(0.2)
67
- pil = [Image.open(p).convert('RGB') for p in paths]
68
- pdf = f"{OUT}/{slug}_ch{chapter}.pdf"
69
- pil[0].save(pdf, save_all=True, append_images=pil[1:])
70
- z = pdf.replace('.pdf', '.7z')
71
- subprocess.run(['7z', 'a', '-t7z', '-mx=9', z, pdf], check=True)
72
- os.remove(pdf)
73
- subprocess.run(['rm', '-rf', ch_dir], check=False)
74
- return FileResponse(z, filename=f"{slug}_ch{chapter}.7z")
 
1
+ from fastapi import FastAPI, Query
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.responses import JSONResponse
4
+ import requests
5
  from bs4 import BeautifulSoup
 
6
  from urllib.parse import quote
7
+ from typing import Optional
8
 
9
  app = FastAPI()
10
+ app.add_middleware(
11
+ CORSMiddleware,
12
+ allow_origins=["*"],
13
+ allow_methods=["*"],
14
+ allow_headers=["*"],
15
+ )
16
 
17
+ BASE = "https://tcbscanmanga.com"
18
+ headers = {"User-Agent": "Mozilla/5.0"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ def soup_get(url):
21
+ r = requests.get(url, headers=headers, timeout=15)
 
 
22
  r.raise_for_status()
23
+ return BeautifulSoup(r.content, "html.parser")
24
+
25
+ @app.get("/manga")
26
+ def list_manga(
27
+ sort: str = Query("latest"),
28
+ q: Optional[str] = None,
29
+ page: int = Query(1, ge=1)
30
+ ):
31
+ if q:
32
+ url = f"{BASE}/search?search={quote(q)}"
33
+ else:
34
+ url = f"{BASE}/manga/" if page == 1 else f"{BASE}/manga/page/{page}/"
35
+ soup = soup_get(url)
36
+ items = []
37
+ for item in soup.select(".c-tabs-item__content, .page-item-detail"):
38
+ a = item.select_one(".post-title a, h3 a, .h4 a")
39
+ if not a:
40
+ continue
41
+ href = a.get("href", "")
42
+ mid = href.rstrip("/").split("/")[-1]
43
+ title = a.get_text(strip=True)
44
+ cover = item.select_one("img")
45
+ cover_url = cover.get("src") or cover.get("data-src") if cover else None
46
+ items.append({"id": mid, "title": title, "cover": cover_url})
47
+ has_more = bool(soup.select_one(".nav-previous, .next, a[rel='next']"))
48
+ return {"items": items, "hasMore": has_more}
49
+
50
+ @app.get("/manga/{id}")
51
+ def manga_detail(id: str):
52
+ soup = soup_get(f"{BASE}/manga/{id}")
53
+ title = soup.select_one("h1")
54
+ cover = soup.select_one(".summary_image img, .tab-thumb img")
55
+ desc = soup.select_one(".description-summary, .summary__content, .manga-excerpt")
56
+ status = soup.select_one(".post-status .summary-content, .status")
57
+ tags = [t.get_text(strip=True) for t in soup.select(".genres-content a, .mg_genres a")]
58
+ return {
59
+ "id": id,
60
+ "title": title.get_text(strip=True) if title else id,
61
+ "cover": (cover.get("src") or cover.get("data-src")) if cover else None,
62
+ "description": desc.get_text(strip=True) if desc else None,
63
+ "status": status.get_text(strip=True) if status else None,
64
+ "tags": tags
65
+ }
66
+
67
+ @app.get("/manga/{id}/chapters")
68
+ def manga_chapters(id: str):
69
+ soup = soup_get(f"{BASE}/manga/{id}")
70
+ chapters = []
71
+ for a in soup.select(".wp-manga-chapter a, .listing-chapters_wrap a"):
72
+ href = a.get("href", "")
73
+ text = a.get_text(strip=True)
74
+ # extract number as string
75
+ num = href.rstrip("/").split("chapter-")[-1] if "chapter-" in href else text
76
+ cid = f"{id}:{num}"
77
+ chapters.append({
78
+ "id": cid,
79
+ "number": str(num),
80
+ "title": text,
81
+ "pages": None,
82
+ "publishedAt": None
83
+ })
84
+ return chapters
85
 
86
+ @app.get("/chapters/{id}/pages")
87
+ def chapter_pages(id: str):
88
+ # id format: slug:number
89
+ if ":" not in id:
90
+ return JSONResponse({"error": "invalid id"}, status_code=400)
91
+ slug, number = id.split(":", 1)
92
+ soup = soup_get(f"{BASE}/manga/{slug}/chapter-{number}")
93
+ pages = []
94
+ for img in soup.find_all("img", {"class": "wp-manga-chapter-img"}):
95
+ src = img.get("src") or img.get("data-src")
96
+ if src:
97
+ if not src.startswith("http"):
98
+ src = BASE + src
99
+ pages.append(src)
100
+ return {"pages": pages}