File size: 12,130 Bytes
233f6bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
ProprScout Geolocation API Server
Flask application serving the hybrid geolocation pipeline
"""

import os
import sys
import logging
import json
from pathlib import Path
from flask import Flask, request, jsonify
from flask.json.provider import DefaultJSONProvider
from flask_cors import CORS
import tempfile
import traceback
import numpy as np


class NumpyJSONProvider(DefaultJSONProvider):
    """Custom JSON provider that handles numpy types"""
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        if isinstance(obj, np.floating):
            return float(obj)
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        return super().default(obj)

# Add parent directory to path for imports
sys.path.insert(0, str(Path(__file__).parent))

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# Flask app
app = Flask(__name__)
app.json = NumpyJSONProvider(app)

# CORS - restrict to Node backend and production frontend only
ALLOWED_ORIGINS = [
    'http://localhost:3002',  # Node backend in dev
    'http://localhost:3000',  # Frontend in dev
    'https://proprscout.com',
    'https://www.proprscout.com',
    'https://app.proprscout.com',
    'https://proprscout.onrender.com'  # Render backend
]
CORS(app, origins=ALLOWED_ORIGINS, supports_credentials=True)

# Configuration
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB max upload
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'webp'}

# Initialize components (lazy loading)
_pipeline = None
_initialization_error = None


def get_pipeline():
    """Lazy load the geolocation pipeline"""
    global _pipeline, _initialization_error

    if _initialization_error:
        raise _initialization_error

    if _pipeline is None:
        logger.info("Initializing geolocation pipeline...")

        try:
            from models.coarse_locator import CoarseLocator
            from models.portugal_embedder import PortugalEmbedder
            from retrieval.faiss_index import PortugalImageIndex
            from gis.building_snapper import BuildingSnapper
            from pipeline.hybrid_predictor import HybridGeoLocator

            # Initialize components
            coarse = CoarseLocator()
            embedder = PortugalEmbedder()

            # Load index if exists
            data_dir = Path(__file__).parent / 'data'
            index_path = data_dir / 'indexes' / 'portugal.faiss'
            meta_path = data_dir / 'indexes' / 'portugal_meta.json'

            if index_path.exists() and meta_path.exists():
                image_index = PortugalImageIndex(str(index_path), str(meta_path))
                logger.info("FAISS index loaded")
            else:
                logger.warning("No FAISS index found - retrieval disabled")
                image_index = PortugalImageIndex()  # Empty index

            snapper = BuildingSnapper(cache_dir=str(data_dir / 'gis_cache'))

            _pipeline = HybridGeoLocator(
                coarse_locator=coarse,
                portugal_embedder=embedder,
                image_index=image_index,
                building_snapper=snapper
            )

            logger.info("Geolocation pipeline initialized successfully")

        except Exception as e:
            logger.error(f"Failed to initialize pipeline: {e}")
            logger.error(traceback.format_exc())
            _initialization_error = e
            raise

    return _pipeline


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def validate_url_ssrf(url):
    """
    SSRF Protection - Block internal/private IP addresses and hostnames
    """
    from urllib.parse import urlparse
    import socket

    try:
        parsed = urlparse(url)
        hostname = parsed.hostname

        if not hostname:
            raise ValueError('Invalid URL: no hostname')

        hostname_lower = hostname.lower()

        # Block localhost variants
        blocked_hostnames = ['localhost', '127.0.0.1', '0.0.0.0', '::1', '[::1]']
        if hostname_lower in blocked_hostnames:
            raise ValueError('Access to localhost is not allowed')

        # Only allow HTTP/HTTPS
        if parsed.scheme not in ['http', 'https']:
            raise ValueError('Only HTTP and HTTPS protocols are allowed')

        # Resolve hostname and check IP
        try:
            ip = socket.gethostbyname(hostname)
            octets = ip.split('.')
            if len(octets) == 4:
                a, b = int(octets[0]), int(octets[1])
                # 10.0.0.0/8
                if a == 10:
                    raise ValueError('Access to private IP addresses is not allowed')
                # 172.16.0.0/12
                if a == 172 and 16 <= b <= 31:
                    raise ValueError('Access to private IP addresses is not allowed')
                # 192.168.0.0/16
                if a == 192 and b == 168:
                    raise ValueError('Access to private IP addresses is not allowed')
                # 169.254.0.0/16 (link-local)
                if a == 169 and b == 254:
                    raise ValueError('Access to link-local addresses is not allowed')
                # 127.0.0.0/8 (loopback)
                if a == 127:
                    raise ValueError('Access to loopback addresses is not allowed')
        except socket.gaierror:
            raise ValueError('Could not resolve hostname')

        return True

    except ValueError:
        raise
    except Exception as e:
        raise ValueError(f'Invalid URL: {str(e)}')


@app.route('/health', methods=['GET'])
@app.route('/api/health', methods=['GET'])
def health_check():
    """Health check endpoint"""
    status = {
        'status': 'healthy',
        'service': 'proprscout-geolocation',
        'version': '1.0.0'
    }

    # Check pipeline status
    try:
        pipeline = get_pipeline()
        status['pipeline'] = 'ready'
        status['components'] = {
            'coarse_locator': pipeline.coarse_locator is not None,
            'portugal_embedder': pipeline.portugal_embedder is not None,
            'image_index': pipeline.image_index.is_available if pipeline.image_index else False,
            'building_snapper': pipeline.building_snapper.is_available if pipeline.building_snapper else False
        }
    except Exception as e:
        status['pipeline'] = 'error'
        status['error'] = str(e)

    return jsonify(status)


@app.route('/api/geolocation/analyze', methods=['POST'])
@app.route('/api/geoclip/predict', methods=['POST'])
def analyze_image():
    """
    Main geolocation endpoint.
    Accepts image file or image URL.
    """
    image_path = None

    try:
        pipeline = get_pipeline()

        # Handle file upload
        if 'image' in request.files:
            file = request.files['image']
            if file.filename == '':
                return jsonify({'error': 'No file selected'}), 400

            if not allowed_file(file.filename):
                return jsonify({'error': 'Invalid file type'}), 400

            # Save to temp file
            with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as tmp:
                file.save(tmp.name)
                image_path = tmp.name

        # Handle URL
        elif request.json and 'image_url' in request.json:
            import requests as req
            from PIL import Image
            from io import BytesIO

            image_url = request.json['image_url']

            # SSRF Protection - validate URL before fetching
            try:
                validate_url_ssrf(image_url)
            except ValueError as e:
                return jsonify({'error': f'Invalid image URL: {str(e)}'}), 400

            response = req.get(image_url, timeout=30)
            response.raise_for_status()

            img = Image.open(BytesIO(response.content))

            with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as tmp:
                img.save(tmp.name)
                image_path = tmp.name

        # Handle base64
        elif request.json and 'image_base64' in request.json:
            import base64
            from PIL import Image
            from io import BytesIO

            image_data = base64.b64decode(request.json['image_base64'])
            img = Image.open(BytesIO(image_data))

            with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as tmp:
                img.save(tmp.name)
                image_path = tmp.name

        else:
            return jsonify({'error': 'No image provided'}), 400

        # Run prediction
        logger.info(f"Processing image: {image_path}")
        result = pipeline.predict(image_path)

        # Format response
        response = {
            'success': True,
            'coordinates': None,
            'confidence': result['confidence'],
            'method': result['method'],
            'building': result.get('building_match'),
            'candidates': []
        }

        if result['best_prediction']:
            response['coordinates'] = {
                'lat': result['best_prediction']['lat'],
                'lon': result['best_prediction']['lon']
            }
            response['prediction_source'] = result['best_prediction'].get('source')

        # Add top candidates
        if result['predictions']:
            response['candidates'] = [
                {
                    'lat': p['lat'],
                    'lon': p['lon'],
                    'cluster_size': p.get('cluster_size', 1),
                    'similarity': p.get('avg_similarity', 0)
                }
                for p in result['predictions'][:5]
            ]

        return jsonify(response)

    except Exception as e:
        logger.error(f"Analysis failed: {e}")
        logger.error(traceback.format_exc())
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

    finally:
        # Clean up temp file
        if image_path:
            try:
                os.unlink(image_path)
            except Exception:
                pass


@app.route('/api/geolocation/feedback', methods=['POST'])
def submit_feedback():
    """
    Accept human correction for failed predictions.
    Used for model improvement.
    """
    try:
        data = request.json

        required = ['image_id', 'correct_lat', 'correct_lon']
        if not all(k in data for k in required):
            return jsonify({'error': 'Missing required fields'}), 400

        # Save feedback for training
        feedback_dir = Path(__file__).parent / 'data' / 'feedback'
        feedback_dir.mkdir(parents=True, exist_ok=True)

        import json
        from datetime import datetime

        feedback_file = feedback_dir / 'corrections.jsonl'
        with open(feedback_file, 'a') as f:
            feedback = {
                'timestamp': datetime.utcnow().isoformat(),
                'image_id': data['image_id'],
                'predicted_lat': data.get('predicted_lat'),
                'predicted_lon': data.get('predicted_lon'),
                'correct_lat': data['correct_lat'],
                'correct_lon': data['correct_lon'],
                'notes': data.get('notes', '')
            }
            f.write(json.dumps(feedback) + '\n')

        return jsonify({'success': True, 'message': 'Feedback recorded'})

    except Exception as e:
        logger.error(f"Feedback failed: {e}")
        return jsonify({'error': str(e)}), 500


if __name__ == '__main__':
    port = int(os.environ.get('PORT', 3001))
    debug = os.environ.get('FLASK_ENV') == 'development'

    logger.info(f"Starting ProprScout Geolocation API on port {port}")

    # Pre-initialize pipeline on startup
    try:
        get_pipeline()
    except Exception as e:
        logger.error(f"Pipeline initialization failed: {e}")
        # Continue anyway - will retry on first request

    app.run(host='0.0.0.0', port=port, debug=debug)