File size: 12,999 Bytes
986a376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
from typing import List, Dict, Optional, Tuple
import time
import json
from pathlib import Path
from datetime import datetime

class OverpassGeocoder:
    def __init__(self, output_dir: str = "output"):
        self.overpass_url = "https://overpass-api.de/api/interpreter"
        self.nominatim_url = "https://nominatim.openstreetmap.org"
        self.headers = {'User-Agent': 'jhbhbbvsio0'}
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(exist_ok=True)
    
    def geocode_location(self, location: str) -> Optional[Tuple[float, float]]:
        """
        Chuyển đổi địa điểm (city, country) thành tọa độ
        """
        print(f"Đang tìm tọa độ cho: {location}")
        
        params = {
            'q': location,
            'format': 'json',
            'limit': 1
        }
        
        try:
            response = requests.get(
                f"{self.nominatim_url}/search",
                params=params,
                headers=self.headers,
                timeout=10
            )
            
            if response.status_code == 200:
                data = response.json()
                if data:
                    lat = float(data[0]['lat'])
                    lon = float(data[0]['lon'])
                    print(f"✓ Tìm thấy: {lat}, {lon}")
                    return (lat, lon)
            
        except Exception as e:
            print(f"Lỗi geocode: {e}")
        
        return None
    
    def get_all_places(self, lat: float, lon: float, radius_meters: int = 3000) -> List[Dict]:
        """
        Lấy tất cả địa điểm trong bán kính
        """
        overpass_query = f"""
        [out:json][timeout:60];
        (
          node["amenity"](around:{radius_meters},{lat},{lon});
          way["amenity"](around:{radius_meters},{lat},{lon});
          node["shop"](around:{radius_meters},{lat},{lon});
          way["shop"](around:{radius_meters},{lat},{lon});
          node["building"]["name"](around:{radius_meters},{lat},{lon});
          way["building"]["name"](around:{radius_meters},{lat},{lon});
          node["healthcare"](around:{radius_meters},{lat},{lon});
          way["healthcare"](around:{radius_meters},{lat},{lon});
          node["leisure"](around:{radius_meters},{lat},{lon});
          way["leisure"](around:{radius_meters},{lat},{lon});
          node["tourism"](around:{radius_meters},{lat},{lon});
          way["tourism"](around:{radius_meters},{lat},{lon});
          node["office"](around:{radius_meters},{lat},{lon});
          way["office"](around:{radius_meters},{lat},{lon});
        );
        out center body;
        """
        
        print(f"Đang truy vấn Overpass API (bán kính {radius_meters}m)...")
        
        try:
            response = requests.post(
                self.overpass_url,
                data={'data': overpass_query},
                timeout=120
            )
            response.raise_for_status()
            data = response.json()
            
            elements = data.get('elements', [])
            print(f"✓ Tìm thấy {len(elements)} địa điểm từ OpenStreetMap")
            return elements
            
        except Exception as e:
            print(f"Lỗi Overpass API: {e}")
            return []
    
    def reverse_geocode(self, lat: float, lon: float) -> Optional[Dict]:
        """
        Lấy địa chỉ chính xác từ tọa độ
        """
        params = {
            'lat': lat,
            'lon': lon,
            'format': 'json',
            'addressdetails': 1,
            'zoom': 18
        }
        
        try:
            response = requests.get(
                f"{self.nominatim_url}/reverse",
                params=params,
                headers=self.headers,
                timeout=10
            )
            
            if response.status_code == 200:
                return response.json()
            
        except Exception as e:
            pass
        
        return None
    
    def get_coordinates(self, element: Dict) -> Optional[Tuple[float, float]]:
        """
        Lấy tọa độ từ element
        """
        if element['type'] == 'node':
            return (element.get('lat'), element.get('lon'))
        elif element['type'] == 'way' and 'center' in element:
            return (element['center'].get('lat'), element['center'].get('lon'))
        return None
    
    def format_address(self, name: str, reverse_data: Dict, seed_city: str, country: str) -> str:
        """
        Format địa chỉ từ reverse geocoding
        """
        if not reverse_data:
            return f"{name}, {seed_city}, {country}"
        
        address = reverse_data.get('address', {})
        
        road = address.get('road', '')
        house_number = address.get('house_number', '')
        suburb = address.get('suburb', '')
        
        # Ưu tiên lấy city thực tế từ reverse geocoding
        city = (address.get('city') or 
                address.get('town') or 
                address.get('village') or 
                address.get('municipality') or
                seed_city)  # Fallback về seed city
        
        parts = [name]
        
        if road:
            if house_number:
                parts.append(f"{house_number} {road}")
            else:
                parts.append(road)
        
        # Chỉ thêm city nếu nó khác seed_city HOẶC là city duy nhất
        if city and city != seed_city:
            parts.append(city)
        elif city == seed_city:
            parts.append(city)
        
        if suburb and suburb != city:
            parts.append(suburb)
        
        parts.append(country)
        
        return ', '.join(parts)
    
    def format_element(self, element: Dict) -> Optional[Dict]:
        """
        Format element từ Overpass
        """
        tags = element.get('tags', {})
        
        name = (tags.get('name') or 
               tags.get('name:en') or
               tags.get('brand') or
               tags.get('operator'))
        
        if not name:
            return None
        
        category = (tags.get('amenity') or
                   tags.get('shop') or
                   tags.get('building') or
                   tags.get('healthcare') or
                   tags.get('leisure') or
                   tags.get('tourism') or
                   tags.get('office') or
                   'unknown')
        
        coords = self.get_coordinates(element)
        
        if not coords or not coords[0] or not coords[1]:
            return None
        
        return {
            'id': element.get('id'),
            'type': element.get('type'),
            'name': name,
            'category': category,
            'lat': coords[0],
            'lon': coords[1],
            'tags': tags
        }
    
    def process_places(self, elements: List[Dict], seed_city: str, country: str, 
                       only_seed_city: bool = True, delay: float = 1.0) -> List[Dict]:
        """
        Xử lý và lấy địa chỉ cho tất cả địa điểm
        
        Args:
            only_seed_city: Nếu True, chỉ giữ địa điểm trong seed city
        """
        # Format và loại bỏ trùng lặp
        unique_places = {}
        for elem in elements:
            formatted = self.format_element(elem)
            if formatted and formatted['name'] not in unique_places:
                unique_places[formatted['name']] = formatted
        
        places = list(unique_places.values())
        total = len(places)
        
        print(f"\nĐang lấy địa chỉ cho {total} địa điểm duy nhất...")
        print("=" * 80)
        
        results = []
        filtered_count = 0
        c=0
        for i, place in enumerate(places, 1):
            print(f"[{i}/{total}] {place['name'][:50]:<50}", end='\r')
            
            reverse_data = self.reverse_geocode(place['lat'], place['lon'])
            c+=1
            if c>100:
                break
            # Kiểm tra city nếu bật filter
            if only_seed_city and reverse_data:
                actual_city = (reverse_data.get('address', {}).get('city') or
                             reverse_data.get('address', {}).get('town') or
                             reverse_data.get('address', {}).get('village') or
                             reverse_data.get('address', {}).get('municipality') or
                             seed_city)
                
                # Chỉ giữ nếu match seed_city (không phân biệt hoa/thường)
                if actual_city.lower() != seed_city.lower():
                    filtered_count += 1
                    time.sleep(delay)
                    continue
            
            address = self.format_address(place['name'], reverse_data, seed_city, country)
            
            place['address'] = address
            place['reverse_data'] = reverse_data.get('address', {}) if reverse_data else {}
            results.append(place)
            
            time.sleep(delay)
        
        print(f"\n{'✓ Hoàn thành!':<80}")
        if filtered_count > 0:
            print(f"  → Đã lọc bỏ {filtered_count} địa điểm ngoài {seed_city}")
        
        return results
    
    def save_results(self, places: List[Dict], location: str):
        """
        Lưu kết quả vào output folder
        """
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        safe_location = location.replace(',', '_').replace(' ', '_')
        
        # Sắp xếp theo tên
        places.sort(key=lambda x: x['name'])
        
        # File địa chỉ đơn giản
        txt_file = self.output_dir / f"{safe_location}_addresses_{timestamp}.txt"
        with open(txt_file, 'w', encoding='utf-8') as f:
            for place in places:
                f.write(place['address'] + '\n')
        print(f"✓ Đã lưu {len(places)} địa chỉ vào: {txt_file}")
        
        # File JSON chi tiết
        json_file = self.output_dir / f"{safe_location}_places_{timestamp}.json"
        with open(json_file, 'w', encoding='utf-8') as f:
            json.dump(places, f, ensure_ascii=False, indent=2)
        print(f"✓ Đã lưu chi tiết vào: {json_file}")
        
        return txt_file, json_file
    
    def print_statistics(self, places: List[Dict], city: str):
        """
        In thống kê
        """
        print("\n" + "=" * 80)
        print("THỐNG KÊ:")
        print("=" * 80)
        
        with_city = sum(1 for p in places if city in p['address'])
        print(f"Có '{city}': {with_city}/{len(places)}")
        
        category_count = {}
        for place in places:
            cat = place['category']
            category_count[cat] = category_count.get(cat, 0) + 1
        
        print("\nTheo loại:")
        for cat, count in sorted(category_count.items(), key=lambda x: x[1], reverse=True)[:10]:
            print(f"  {cat:30s}: {count:3d}")
    
    def run(self, location: str, radius_meters: int = 3000, delay: float = 1.0):
        """
        Chạy toàn bộ quy trình
        
        Args:
            location: Định dạng "City, Country" (vd: "Victoria, Seychelles")
            radius_meters: Bán kính tìm kiếm (mặc định 3000m)
            delay: Thời gian chờ giữa các request (mặc định 1.0s)
        """
        print("=" * 80)
        print(f"GEOCODER - {location.upper()}")
        print("=" * 80)
        
        # Lấy tọa độ
        coords = self.geocode_location(location)
        if not coords:
            print("✗ Không tìm thấy tọa độ cho địa điểm này!")
            return
        
        lat, lon = coords
        city = location.split(',')[0].strip()
        country = location.split(',')[-1].strip()
        
        # Lấy địa điểm từ Overpass
        elements = self.get_all_places(lat, lon, radius_meters)
        if not elements:
            print("✗ Không tìm thấy địa điểm nào!")
            return
        
        # Xử lý và lấy địa chỉ
        places = self.process_places(elements, city, country, delay)
        
        # Lưu kết quả
        self.save_results(places, location)
        
        # Hiển thị thống kê
        self.print_statistics(places, city)
        
        print("\n" + "=" * 80)
        print("✓ HOÀN THÀNH!")
        print("=" * 80)


if __name__ == "__main__":
    # Khởi tạo geocoder
    geocoder = OverpassGeocoder(output_dir="output")
    
    # Chạy với seed location
    geocoder.run(
        location="Grytviken, South Georgia and the South Sandwich Islands",
        radius_meters=3000,
        delay=1.0
    )
    
    # Ví dụ khác:
    # geocoder.run("Paris, France", radius_meters=5000)
    # geocoder.run("Hanoi, Vietnam", radius_meters=2000)