File size: 9,505 Bytes
61d29fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Platform detection for municipal websites.

Based on patterns from:
- biglocalnews/civic-scraper (Apache 2.0)
- city-scrapers/city-scrapers (MIT)

Detects which content management system or meeting platform a municipality uses,
enabling optimized scraping strategies.
"""
from typing import Optional, Dict, List
from urllib.parse import urlparse
import httpx
from bs4 import BeautifulSoup
from loguru import logger


# Platform URL patterns (most specific first)
PLATFORM_PATTERNS = {
    'legistar': [
        'legistar.com',
        '/Legistar/',
        '/LegislationDetail.aspx',
        '/Calendar.aspx',
        '/MeetingDetail.aspx',
        'WebApi/odata'
    ],
    'granicus': [
        'granicus.com',
        '/Mediasite/',
        '/ViewPublisher.php',
        '/MetaViewer.php',
        'granicus-cdn.com'
    ],
    'municode': [
        'municode.com',
        '/meeting_minutes',
        '/MuniCode/'
    ],
    'civicplus': [
        'civicplus.com',
        '/AgendaCenter/',
        '/DocumentCenter/',
        '/CivicSend/'
    ],
    'primegov': [
        'primegov.com',
        '/Portal/',
        '/Public/0/'
    ],
    'calagenda': [
        'ca-ilg.civicplus.com',
        '/AgendaCenter/ViewFile/'
    ],
    'swagit': [
        'swagit.com',
        '/play/',
        '/videos/'
    ],
    'zoomgov': [
        'zoom.us/rec/',
        'zoomgov.com'
    ]
}

# HTML meta tag patterns that indicate platforms
META_PATTERNS = {
    'legistar': [
        'Legistar',
        'InSite',
        'Granicus'  # Granicus owns Legistar
    ],
    'civicplus': [
        'CivicPlus',
        'CivicEngage'
    ]
}

# Common CMS patterns (WordPress, Drupal, etc.)
CMS_PATTERNS = {
    'wordpress': [
        'wp-content',
        'wp-includes',
        'wordpress'
    ],
    'drupal': [
        '/sites/default/',
        'drupal.js',
        'Drupal.settings'
    ],
    'joomla': [
        '/components/com_',
        '/modules/mod_'
    ]
}


def detect_platform(url: str, html_content: Optional[str] = None) -> Optional[str]:
    """
    Detect which platform a municipality website uses.
    
    Performs two-stage detection:
    1. URL pattern matching (fast, works without fetching)
    2. HTML content analysis (slower, more accurate)
    
    Args:
        url: Municipality website URL
        html_content: Optional HTML content for deeper analysis
        
    Returns:
        Platform name or None if unknown
        
    Examples:
        >>> detect_platform("https://chicago.legistar.com/Calendar.aspx")
        'legistar'
        >>> detect_platform("https://example.gov/meetings")
        None
    """
    url_lower = url.lower()
    
    # Stage 1: URL pattern matching
    for platform, patterns in PLATFORM_PATTERNS.items():
        if any(pattern.lower() in url_lower for pattern in patterns):
            logger.debug(f"Detected {platform} from URL pattern: {url}")
            return platform
    
    # Stage 2: HTML content analysis (if provided)
    if html_content:
        platform = detect_from_html(html_content)
        if platform:
            logger.debug(f"Detected {platform} from HTML content: {url}")
            return platform
    
    # Stage 3: Check for generic CMS
    for cms, patterns in CMS_PATTERNS.items():
        if any(pattern.lower() in url_lower for pattern in patterns):
            logger.debug(f"Detected generic CMS {cms}: {url}")
            return 'generic'
    
    logger.debug(f"No platform detected for: {url}")
    return None


def detect_from_html(html_content: str) -> Optional[str]:
    """
    Detect platform from HTML content analysis.
    
    Checks:
    - Meta tags (generator, description)
    - Script sources
    - Link hrefs
    - Specific HTML structures
    
    Args:
        html_content: Raw HTML content
        
    Returns:
        Platform name or None
    """
    try:
        soup = BeautifulSoup(html_content, 'html.parser')
        
        # Check meta tags
        for platform, keywords in META_PATTERNS.items():
            meta_generator = soup.find('meta', attrs={'name': 'generator'})
            if meta_generator:
                content = meta_generator.get('content', '').lower()
                if any(keyword.lower() in content for keyword in keywords):
                    return platform
        
        # Check scripts and links
        all_text = html_content.lower()
        for platform, patterns in PLATFORM_PATTERNS.items():
            if any(pattern.lower() in all_text for pattern in patterns):
                return platform
        
    except Exception as e:
        logger.warning(f"Error parsing HTML for platform detection: {e}")
    
    return None


async def detect_platform_async(url: str, fetch_html: bool = True) -> Dict[str, any]:
    """
    Async version that can fetch HTML content for deeper detection.
    
    Args:
        url: Municipality website URL
        fetch_html: Whether to fetch HTML for content analysis
        
    Returns:
        Dictionary with detection results:
        {
            'platform': str,
            'confidence': float,
            'features': List[str],
            'scraper_available': bool
        }
    """
    result = {
        'url': url,
        'platform': None,
        'confidence': 0.0,
        'features': [],
        'scraper_available': False
    }
    
    # Quick URL check
    platform = detect_platform(url)
    if platform:
        result['platform'] = platform
        result['confidence'] = 0.7
        result['features'].append('url_pattern')
    
    # Fetch and analyze HTML if requested
    if fetch_html:
        try:
            async with httpx.AsyncClient(timeout=10.0) as client:
                response = await client.get(url, follow_redirects=True)
                response.raise_for_status()
                
                platform_from_html = detect_from_html(response.text)
                if platform_from_html:
                    result['platform'] = platform_from_html
                    result['confidence'] = 0.9
                    result['features'].append('html_content')
                    
        except Exception as e:
            logger.warning(f"Could not fetch {url} for platform detection: {e}")
    
    # Check if we have a scraper for this platform
    if result['platform'] in ['legistar', 'granicus', 'civicplus']:
        result['scraper_available'] = True
    
    return result


def get_platform_capabilities(platform: str) -> Dict[str, any]:
    """
    Get capabilities and scraping strategies for a platform.
    
    Args:
        platform: Platform name
        
    Returns:
        Dictionary describing platform capabilities
    """
    capabilities = {
        'legistar': {
            'has_api': True,
            'api_docs': 'https://webapi.legistar.com/Help',
            'supports_bulk_download': True,
            'common_endpoints': [
                '/events',
                '/matters',
                '/bodies'
            ],
            'rate_limit': 'Unknown',
            'scraper_class': 'scrapers.legistar.LegistarScraper'
        },
        'granicus': {
            'has_api': True,
            'supports_bulk_download': True,
            'common_endpoints': [
                '/ViewPublisher.php',
                '/MetaViewer.php'
            ],
            'rate_limit': 'Unknown',
            'scraper_class': 'scrapers.granicus.GranicusScraper'
        },
        'civicplus': {
            'has_api': False,
            'supports_bulk_download': False,
            'requires_html_parsing': True,
            'scraper_class': 'scrapers.civicplus.CivicPlusScraper'
        },
        'generic': {
            'has_api': False,
            'supports_bulk_download': False,
            'requires_html_parsing': True,
            'scraper_class': 'scrapers.generic.GenericScraper'
        }
    }
    
    return capabilities.get(platform, {
        'has_api': False,
        'supports_bulk_download': False,
        'requires_html_parsing': True,
        'scraper_class': 'scrapers.generic.GenericScraper'
    })


def get_scraper_class(platform: str):
    """
    Get appropriate scraper class for a platform.
    
    Args:
        platform: Platform name
        
    Returns:
        Scraper class (dynamically imported)
    """
    # Note: This assumes you'll create these scraper classes
    # For now, returns None to avoid import errors
    
    scraper_map = {
        'legistar': 'scrapers.legistar.LegistarScraper',
        'granicus': 'scrapers.granicus.GranicusScraper',
        'civicplus': 'scrapers.civicplus.CivicPlusScraper',
        'generic': 'scrapers.generic.GenericScraper'
    }
    
    scraper_path = scraper_map.get(platform, 'scrapers.generic.GenericScraper')
    
    # TODO: Dynamic import when scrapers are implemented
    # module_path, class_name = scraper_path.rsplit('.', 1)
    # module = importlib.import_module(module_path)
    # return getattr(module, class_name)
    
    logger.warning(f"Scraper class not yet implemented: {scraper_path}")
    return None


# Example usage
if __name__ == "__main__":
    # Test URL detection
    test_urls = [
        "https://chicago.legistar.com/Calendar.aspx",
        "https://birminghamal.gov/meetings",
        "https://example.civicplus.com/AgendaCenter",
        "https://unknown-city.gov/council"
    ]
    
    for url in test_urls:
        platform = detect_platform(url)
        print(f"{url}\n  → Platform: {platform}\n")