File size: 7,835 Bytes
37a9ecb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Modèles Pydantic v2 - typage strict, computed fields, validators.
"""

from __future__ import annotations

import hashlib
from datetime import datetime, timezone
from enum import Enum
from typing import Annotated, Any, Optional
from urllib.parse import urlparse

from pydantic import (
    AnyHttpUrl,
    BaseModel,
    ConfigDict,
    Field,
    computed_field,
    field_validator,
    model_validator,
)
from pydantic_settings import BaseSettings, SettingsConfigDict

# ---------------------------------------------------------------------------
# Enums
# ---------------------------------------------------------------------------


class ScrapingMethod(str, Enum):
    AUTO = "auto"
    SCRAPY = "scrapy"
    CURL_CFFI = "curl_cffi"
    CLOUDSCRAPER = "cloudscraper"
    HTTPX = "httpx"


class ExtractionMode(str, Enum):
    RAW = "raw"
    CLEAN = "clean"
    MAIN_CONTENT = "main_content"
    FULL = "full"


# ---------------------------------------------------------------------------
# Settings (pydantic-settings v2)
# ---------------------------------------------------------------------------


class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
    )

    port: int = 7860
    worker_id: str = "scraper-1"
    environment: str = "production"

    # Concurrency
    max_concurrent_requests: Annotated[int, Field(ge=1, le=500)] = 100
    scrapy_concurrent_requests: Annotated[int, Field(ge=1, le=64)] = 16
    scrapy_concurrent_per_domain: Annotated[int, Field(ge=1, le=32)] = 8
    scrapy_download_delay: float = 0.0  # seconds between requests per domain

    # Timeouts
    request_timeout: Annotated[int, Field(ge=5, le=120)] = 30

    # HTTP
    user_agent: str = (
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
        "AppleWebKit/537.36 (KHTML, like Gecko) "
        "Chrome/121.0.0.0 Safari/537.36"
    )
    max_retries: Annotated[int, Field(ge=1, le=5)] = 3
    retry_backoff: Annotated[float, Field(ge=0.1, le=5.0)] = 1.0
    follow_redirects: bool = True
    verify_ssl: bool = True

    # Content
    max_content_size: int = 50_000_000

    # Cache
    enable_cache: bool = True
    cache_ttl: int = 3600
    cache_max_size: int = 1000

    # Extraction
    max_links: int = 500
    max_images: int = 100


# ---------------------------------------------------------------------------
# Request models
# ---------------------------------------------------------------------------

PositiveInt = Annotated[int, Field(gt=0)]
TimeoutInt = Annotated[int, Field(ge=5, le=120)]


class CacheConfig(BaseModel):
    model_config = ConfigDict(frozen=True)

    enabled: bool = True
    ttl: Optional[PositiveInt] = None
    force_refresh: bool = False


class ExtractionConfig(BaseModel):
    model_config = ConfigDict(frozen=True)

    mode: ExtractionMode = ExtractionMode.MAIN_CONTENT
    include_metadata: bool = True
    include_links: bool = False
    include_images: bool = False
    normalize_text: bool = True
    detect_language: bool = True
    css_selectors: Optional[list[str]] = None
    xpath_selectors: Optional[list[str]] = None


class ScrapeOptions(BaseModel):
    model_config = ConfigDict(frozen=True)

    method: ScrapingMethod = ScrapingMethod.AUTO
    headers: Optional[dict[str, str]] = None
    timeout: Optional[TimeoutInt] = None
    verify_ssl: Optional[bool] = None
    follow_redirects: Optional[bool] = None
    extraction: ExtractionConfig = Field(default_factory=ExtractionConfig)
    cache: CacheConfig = Field(default_factory=CacheConfig)


class ScrapeRequest(BaseModel):
    model_config = ConfigDict(frozen=True)

    url: AnyHttpUrl
    options: ScrapeOptions = Field(default_factory=ScrapeOptions)

    @field_validator("url", mode="before")
    @classmethod
    def reject_non_http_files(cls, v: Any) -> Any:
        url_str = str(v)
        blocked = {
            ".pdf", ".zip", ".exe", ".dmg", ".pkg",
            ".jpg", ".jpeg", ".png", ".gif", ".svg", ".webp",
            ".mp4", ".avi", ".mov", ".mp3", ".wav",
            ".css", ".woff", ".woff2", ".ttf",
        }
        path = urlparse(url_str).path.lower()
        if any(path.endswith(ext) for ext in blocked):
            raise ValueError(f"Extension non scrapable : {url_str}")
        return v


# ---------------------------------------------------------------------------
# Response models
# ---------------------------------------------------------------------------


class ContentData(BaseModel):
    raw_html: Optional[str] = None
    clean_html: Optional[str] = None
    text: Optional[str] = None
    title: Optional[str] = None
    author: Optional[str] = None
    date: Optional[str] = None
    description: Optional[str] = None
    language: Optional[str] = None
    word_count: Optional[int] = None

    @computed_field  # type: ignore[misc]
    @property
    def content_hash(self) -> Optional[str]:
        if self.text:
            return hashlib.sha256(self.text.encode()).hexdigest()
        return None


class MetadataData(BaseModel):
    og_data: Optional[dict[str, str]] = None
    twitter_data: Optional[dict[str, str]] = None
    meta_tags: Optional[dict[str, str]] = None
    canonical_url: Optional[str] = None


class LinkItem(BaseModel):
    url: str
    text: str = ""
    rel: str = ""
    title: str = ""


class ImageItem(BaseModel):
    url: str
    alt: str = ""
    title: str = ""
    width: str = ""
    height: str = ""


class LinksData(BaseModel):
    internal: list[LinkItem] = Field(default_factory=list)
    external: list[LinkItem] = Field(default_factory=list)

    @computed_field  # type: ignore[misc]
    @property
    def total_count(self) -> int:
        return len(self.internal) + len(self.external)


class ImagesData(BaseModel):
    images: list[ImageItem] = Field(default_factory=list)

    @computed_field  # type: ignore[misc]
    @property
    def total_count(self) -> int:
        return len(self.images)


class PerformanceMetrics(BaseModel):
    total_time: float
    download_time: float
    parsing_time: float
    extraction_time: float
    content_size: int
    cache_hit: bool = False
    scrapy_used: bool = False

    @computed_field  # type: ignore[misc]
    @property
    def throughput_kbps(self) -> float:
        if self.download_time > 0:
            return round(self.content_size / 1024 / self.download_time, 2)
        return 0.0


class ScrapeResponse(BaseModel):
    success: bool
    worker_id: str
    url: str
    final_url: Optional[str] = None
    status_code: Optional[int] = None
    method_used: Optional[ScrapingMethod] = None
    content: Optional[ContentData] = None
    metadata: Optional[MetadataData] = None
    links: Optional[LinksData] = None
    images: Optional[ImagesData] = None
    performance: PerformanceMetrics
    error: Optional[str] = None
    timestamp: str = Field(
        default_factory=lambda: datetime.now(timezone.utc).isoformat()
    )

    @model_validator(mode="after")
    def error_requires_failure(self) -> "ScrapeResponse":
        if self.error and self.success:
            raise ValueError("Un ScrapeResponse avec error doit avoir success=False")
        return self


class HealthResponse(BaseModel):
    status: str = "healthy"
    worker_id: str
    uptime_seconds: float
    total_requests: int
    active_requests: int
    cache_size: int
    cache_hit_rate: float
    avg_response_time: float
    error_rate: float
    methods_available: list[ScrapingMethod] = Field(
        default_factory=lambda: list(ScrapingMethod)
    )

    @computed_field  # type: ignore[misc]
    @property
    def is_degraded(self) -> bool:
        return self.error_rate > 0.3 or self.status != "healthy"


# Singleton settings
settings = Settings()