File size: 14,754 Bytes
68f428f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
"""
Swift Scraper API β€” Hugging Face Spaces Edition
=================================================
FastAPI: Private SearxNG meta-search β†’ concurrent scraping (trafilatura +
semaphore + asyncio.to_thread) β†’ Cerebras LLM cascade (gpt-oss-120b β†’ llama3.1-8b).

Deployed on: HF Spaces (cpu-basic, 16GB RAM)
Port: 7860 (HF requirement)
"""

from __future__ import annotations

import asyncio
import gc
import logging
import os
import sys
import time
from urllib.parse import urlparse

import httpx
import trafilatura
from fastapi import FastAPI, Header, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field

# ─────────────────────────── Logging ────────────────────────────
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)-7s | %(message)s",
    datefmt="%H:%M:%S",
    stream=sys.stdout,
)
log = logging.getLogger("swift-scraper")

# ─────────────────────────── App ────────────────────────────────
app = FastAPI(
    title="Swift Scraper API",
    version="2.0.0",
    docs_url="/docs",
    redoc_url=None,
)

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

# ═══════════════════════════════════════════════════════════════
# CONSTANTS & TUNABLES
# ═══════════════════════════════════════════════════════════════

# Our private SearxNG instance on HF Spaces (no rate limits!)
SEARXNG_URL: str = os.environ.get(
    "SEARXNG_URL",
    "https://sandeepmudhiraj-private-searxng.hf.space",
)

MAX_URLS: int = 50                 # hard cap β€” protects Cerebras context window
SCRAPE_SEMAPHORE_LIMIT: int = 12   # max concurrent outbound scrape connections
SCRAPE_TIMEOUT_SEC: float = 6.0    # per-URL hard timeout
MAX_CONTEXT_CHARS: int = 80_000    # hard-slice before LLM call
CEREBRAS_API_URL: str = "https://api.cerebras.ai/v1/chat/completions"

# LLM fallback cascade
CEREBRAS_MODEL_CASCADE: list[str] = [
    "gpt-oss-120b",    # Priority 1 β€” reasoning model (120B)
    "llama3.1-8b",     # Priority 2 β€” lightweight fallback (8B)
]

_UA = "Mozilla/5.0 (compatible; SwiftScraperBot/2.0)"
_HEADERS = {"User-Agent": _UA}


# ─────────────────── Pydantic Models ───────────────────────────
class SearchRequest(BaseModel):
    query: str = Field(..., min_length=1, max_length=1000)


class SearchResponse(BaseModel):
    query: str
    sources_found: int
    sources_scraped: int
    answer: str
    model_used: str
    citations: list[str]
    elapsed_seconds: float


# ═══════════════════════════════════════════════════════════════
# PHASE 1 β€” META-SEARCH (Private SearxNG)
# ═══════════════════════════════════════════════════════════════

async def meta_search(query: str) -> list[str]:
    """Query our private SearxNG instance.  Returns up to MAX_URLS unique URLs."""
    seen: set[str] = set()
    unique_urls: list[str] = []

    params = {
        "q": query,
        "format": "json",
        "categories": "general",
        "language": "en",
        "pageno": 1,
    }

    async with httpx.AsyncClient(follow_redirects=True) as client:
        try:
            resp = await client.get(
                f"{SEARXNG_URL.rstrip('/')}/search",
                params=params,
                headers=_HEADERS,
                timeout=15.0,
            )
            resp.raise_for_status()
            data = resp.json()
            for result in data.get("results", []):
                url = result.get("url", "").strip()
                if url and url.startswith("http"):
                    parsed = urlparse(url)
                    key = f"{parsed.netloc}{parsed.path}".lower().rstrip("/")
                    if key not in seen:
                        seen.add(key)
                        unique_urls.append(url)
                    if len(unique_urls) >= MAX_URLS:
                        break
        except Exception as exc:
            log.error("SearxNG query failed: %s", exc)

    log.info("Meta-search returned %d unique URLs for: %s", len(unique_urls), query[:80])
    return unique_urls


# ═══════════════════════════════════════════════════════════════
# PHASE 2 β€” CONCURRENT SCRAPING (OOM-Safe)
# ═══════════════════════════════════════════════════════════════

_scrape_semaphore: asyncio.Semaphore | None = None


def _get_semaphore() -> asyncio.Semaphore:
    global _scrape_semaphore
    if _scrape_semaphore is None:
        _scrape_semaphore = asyncio.Semaphore(SCRAPE_SEMAPHORE_LIMIT)
    return _scrape_semaphore


def _extract_text_sync(html: str, url: str) -> str:
    try:
        text = trafilatura.extract(
            html,
            include_comments=False,
            include_tables=False,
            no_fallback=True,
            url=url,
        )
        return text or ""
    except Exception:
        return ""


async def _scrape_single_url(client: httpx.AsyncClient, url: str) -> tuple[str, str]:
    sem = _get_semaphore()
    async with sem:
        try:
            resp = await client.get(
                url,
                headers=_HEADERS,
                timeout=SCRAPE_TIMEOUT_SEC,
                follow_redirects=True,
            )
            if resp.status_code != 200:
                return url, ""
            content_type = resp.headers.get("content-type", "")
            if "text/html" not in content_type and "text/plain" not in content_type:
                return url, ""
            html = resp.text
            text = await asyncio.to_thread(_extract_text_sync, html, url)
            return url, text
        except Exception:
            return url, ""


async def scrape_urls(urls: list[str]) -> list[tuple[str, str]]:
    results: list[tuple[str, str]] = []
    async with httpx.AsyncClient(
        follow_redirects=True,
        limits=httpx.Limits(max_connections=SCRAPE_SEMAPHORE_LIMIT, max_keepalive_connections=5),
    ) as client:
        tasks = [_scrape_single_url(client, url) for url in urls]
        raw = await asyncio.gather(*tasks, return_exceptions=True)
        for item in raw:
            if isinstance(item, BaseException):
                results.append(("", ""))
            else:
                results.append(item)

    # ── MANDATORY MEMORY CLEANUP ──
    del tasks, raw
    gc.collect()

    return results


# ═══════════════════════════════════════════════════════════════
# PHASE 3 β€” LLM SYNTHESIS (Cerebras Cascade)
# ═══════════════════════════════════════════════════════════════

def _build_context_block(scraped: list[tuple[str, str]]) -> tuple[str, list[str]]:
    parts: list[str] = []
    citations: list[str] = []
    char_count = 0

    for idx, (url, text) in enumerate(scraped, 1):
        if not text or len(text.strip()) < 50:
            continue
        snippet = text.strip()
        marker = f"\n\n--- Source [{idx}]: {url} ---\n{snippet}"
        if char_count + len(marker) > MAX_CONTEXT_CHARS:
            remaining = MAX_CONTEXT_CHARS - char_count
            if remaining > 200:
                parts.append(marker[:remaining])
                citations.append(url)
            break
        parts.append(marker)
        citations.append(url)
        char_count += len(marker)

    context = "".join(parts)
    del parts
    gc.collect()
    return context, citations


def _build_system_prompt() -> str:
    return (
        "You are an advanced research assistant. "
        "Using ONLY the provided source context below, write a comprehensive, "
        "highly detailed, and well-structured answer to the user's query. "
        "Include inline citations in the format [Source N](url) where possible. "
        "If the context is insufficient, state what is known and what could not be verified. "
        "Do NOT fabricate information beyond what the sources provide."
    )


async def _try_cerebras_model(model: str, query: str, context: str, api_key: str) -> str:
    payload = {
        "model": model,
        "messages": [
            {"role": "system", "content": _build_system_prompt()},
            {
                "role": "user",
                "content": (
                    f"## Query\n{query}\n\n"
                    f"## Source Context\n{context}\n\n"
                    "Now write your comprehensive answer with inline citations."
                ),
            },
        ],
        "temperature": 0.3,
        "max_tokens": 4096,
        "stream": False,
    }
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}",
    }

    async with httpx.AsyncClient() as client:
        try:
            resp = await client.post(CEREBRAS_API_URL, json=payload, headers=headers, timeout=30.0)
            if resp.status_code == 401:
                raise HTTPException(status_code=401, detail="Invalid Cerebras API key.")
            if resp.status_code == 429:
                raise HTTPException(status_code=429, detail="Cerebras rate limit hit.")
            resp.raise_for_status()
            data = resp.json()
            msg = data.get("choices", [{}])[0].get("message", {})
            answer = (msg.get("content", "") or msg.get("reasoning", "") or "").strip()
            if not answer:
                raise ValueError(f"Model {model} returned empty response")
            return answer
        except HTTPException:
            raise
        except Exception as exc:
            log.warning("Model '%s' failed: %s", model, exc)
            raise
        finally:
            del payload
            gc.collect()


async def synthesize_with_cerebras(
    query: str, context: str, citations: list[str], api_key: str
) -> tuple[str, str]:
    if not context.strip():
        return (
            "I was unable to extract meaningful content from the search results. "
            "Please try rephrasing your query or try again later.",
            "none",
        )

    last_error: Exception | None = None
    for model in CEREBRAS_MODEL_CASCADE:
        try:
            log.info("Trying model: %s", model)
            answer = await _try_cerebras_model(model, query, context, api_key)
            log.info("Model '%s' succeeded", model)
            return answer, model
        except HTTPException:
            raise
        except Exception as exc:
            last_error = exc
            log.warning("Model '%s' failed, trying next...", model)
            continue

    raise HTTPException(status_code=502, detail=f"All models failed. Last: {last_error}")


# ═══════════════════════════════════════════════════════════════
# ENDPOINTS
# ═══════════════════════════════════════════════════════════════

@app.api_route("/", methods=["GET", "HEAD"])
async def root():
    """Root endpoint for UptimeRobot pings."""
    return {"status": "ok", "service": "Swift Scraper API"}


@app.api_route("/health", methods=["GET", "HEAD"])
async def health():
    return {"status": "ok"}


@app.post("/search", response_model=SearchResponse)
async def search(body: SearchRequest, x_api_key: str = Header(..., alias="x-api-key")):
    t0 = time.perf_counter()
    query = body.query.strip()
    log.info("━━━ NEW SEARCH ━━━  query=%s", query[:100])

    # Phase 1: Meta-Search
    urls = await meta_search(query)
    if not urls:
        raise HTTPException(status_code=404, detail="No search results found.")
    sources_found = len(urls)

    # Phase 2: Scrape
    scraped = await scrape_urls(urls)
    sources_scraped = sum(1 for _, text in scraped if text and len(text.strip()) >= 50)
    log.info("Scraped %d / %d URLs", sources_scraped, sources_found)
    del urls
    gc.collect()

    # Phase 3: Synthesize
    context, citations = _build_context_block(scraped)
    del scraped
    gc.collect()

    answer, model_used = await synthesize_with_cerebras(query, context, citations, x_api_key)
    del context
    gc.collect()

    elapsed = round(time.perf_counter() - t0, 2)
    log.info("━━━ DONE ━━━  model=%s  elapsed=%.2fs  sources=%d/%d",
             model_used, elapsed, sources_scraped, sources_found)

    return SearchResponse(
        query=query,
        sources_found=sources_found,
        sources_scraped=sources_scraped,
        answer=answer,
        model_used=model_used,
        citations=citations,
        elapsed_seconds=elapsed,
    )


@app.exception_handler(Exception)
async def _global_exc_handler(request: Request, exc: Exception):
    log.exception("Unhandled error: %s", exc)
    gc.collect()
    return JSONResponse(status_code=500, content={"detail": "Internal server error."})


# ─────────────────── Entrypoint ─────────────────────────────────
if __name__ == "__main__":
    import uvicorn

    port = int(os.environ.get("PORT", 7860))
    log.info("Starting Swift Scraper API on port %d", port)
    log.info("SearxNG: %s", SEARXNG_URL)
    log.info("LLM cascade: %s", " β†’ ".join(CEREBRAS_MODEL_CASCADE))
    uvicorn.run(
        "app:app",
        host="0.0.0.0",
        port=port,
        workers=1,
        log_level="info",
        access_log=False,
    )