File size: 6,578 Bytes
30f2952
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import os
from typing import Literal, Optional

from fastapi import FastAPI, Query, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

from gallery_scraper import GalleryScraper

app = FastAPI(
    title="Perchance Gallery API",
    version="1.0.0",
    description="FastAPI server for Perchance gallery scraping",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
def root():
    return {
        "ok": True,
        "service": "Perchance Gallery API",
        "endpoints": {
            "/api/gallery": "Fetch gallery data",
            "/health": "Health check",
        },
    }


@app.get("/health")
def health():
    return {"status": "ok"}


@app.get("/api/gallery")
def api_gallery(
    page: int = Query(1, ge=1, description="Starting page, 1-based"),
    pages: int = Query(1, ge=1, le=50, description="How many pages to fetch"),
    sort: Literal["recent", "trending", "top"] = Query("top"),
    timeRange: Literal["all-time", "1-month"] = Query("all-time"),
    contentFilter: Literal["none", "pg13"] = Query("none"),
    concurrency: int = Query(1, ge=1, le=16),
    timeout: int = Query(30, ge=5, le=120),
    save: Optional[str] = Query(None, description="Optional local file path to save JSON"),
):
    """
    Example:
      /api/gallery?page=1&pages=3&sort=top&timeRange=all-time&contentFilter=none
    """

    try:
        start_page = page - 1

        scraper = GalleryScraper(
            pages=pages,
            sort=sort,
            time_range=timeRange,
            content_filter=contentFilter,
            concurrency=concurrency,
            timeout=timeout,
            save=save if save else False,
        )

        # Re-map pages so the scraper starts from the requested page.
        # We do this by reusing the built params behavior in a small wrapper below.
        data = _fetch_from_start_page(
            start_page=start_page,
            pages=pages,
            sort=sort,
            time_range=timeRange,
            content_filter=contentFilter,
            concurrency=concurrency,
            timeout=timeout,
        )

        return JSONResponse(
            {
                "ok": True,
                "page": page,
                "pages": pages,
                "sort": sort,
                "timeRange": timeRange,
                "contentFilter": contentFilter,
                "count": len(data),
                "data": data,
            }
        )

    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Server error: {e}")


def _fetch_from_start_page(
    start_page: int,
    pages: int,
    sort: str,
    time_range: str,
    content_filter: str,
    concurrency: int,
    timeout: int,
):
    """
    Helper that fetches from an arbitrary starting page.
    """
    from concurrent.futures import ThreadPoolExecutor, as_completed
    import time
    import cloudscraper
    from bs4 import BeautifulSoup
    from html import unescape

    GALLERY_URL = "https://image-generation.perchance.org/gallery"
    PER_PAGE = 200

    headers = {
        "User-Agent": (
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
            "AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/145.0.0.0 Safari/537.36"
        ),
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Referer": "https://image-generation.perchance.org/",
        "Origin": "https://image-generation.perchance.org",
    }

    def clean(value):
        if value is None:
            return ""
        return unescape(str(value)).replace("\r", "\n").strip()

    def build_params(page_index: int):
        skip = page_index * PER_PAGE
        params = {
            "sort": sort,
            "timeRange": time_range,
            "hideIfScoreIsBelow": "-1",
            "contentFilter": content_filter,
            "subChannel": "public",
            "channel": "ai-text-to-image-generator",
        }
        if skip > 0:
            params["skip"] = skip
        return params

    def parse_page(html: str):
        if not html:
            return []
        soup = BeautifulSoup(html, "html.parser")
        items = []

        for card in soup.select(".imageCtn"):
            prompt = clean(card.get("data-prompt"))
            negative_prompt = clean(card.get("data-negative-prompt"))
            guidance_scale = clean(card.get("data-guidance-scale"))
            seed = clean(card.get("data-seed"))
            nsfw = clean(card.get("data-is-nsfw")).lower() == "true"
            title_attr = clean(card.get("data-title"))

            img_tag = card.select_one(".imageWrapperInner img.image")
            image_url = img_tag.get("src", "") if img_tag else ""

            title_el = card.select_one(".image-title")
            visible_title = clean(title_el.get_text(" ", strip=True)) if title_el else ""

            item = {
                "image_url": image_url,
                "title": title_attr or visible_title,
                "prompt": prompt,
                "guidance_scale": guidance_scale,
                "seed": seed,
                "nsfw": nsfw,
            }
            if negative_prompt:
                item["negative_prompt"] = negative_prompt
            items.append(item)

        return items

    scraper = cloudscraper.create_scraper()
    results = {}

    def fetch_one(i: int):
        page_index = start_page + i
        try:
            resp = scraper.get(
                GALLERY_URL,
                params=build_params(page_index),
                headers=headers,
                timeout=timeout,
            )
            if resp.status_code != 200:
                return i, []
            return i, parse_page(resp.text)
        except Exception:
            return i, []

    if concurrency <= 1:
        for i in range(pages):
            _, items = fetch_one(i)
            results[i] = items
    else:
        with ThreadPoolExecutor(max_workers=concurrency) as pool:
            futures = [pool.submit(fetch_one, i) for i in range(pages)]
            for future in as_completed(futures):
                i, items = future.result()
                results[i] = items

    merged = []
    for i in range(pages):
        merged.extend(results.get(i, []))

    for idx, item in enumerate(merged, start=1):
        item["no"] = idx

    return merged