-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathosm.py
More file actions
2964 lines (2505 loc) · 117 KB
/
Copy pathosm.py
File metadata and controls
2964 lines (2505 loc) · 117 KB
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
title: OpenStreetMap Tool
author: projectmoon
author_url: https://git.agnos.is/projectmoon/open-webui-filters
version: 4.1.4
license: AGPL-3.0+
required_open_webui_version: 0.6.31
requirements: openrouteservice, pygments
"""
import itertools
import json
import math
import requests
from fastapi.responses import HTMLResponse
from pygments import highlight
from pygments.lexers import JsonLexer
from pygments.formatters import HtmlFormatter
import openrouteservice
from openrouteservice.directions import directions as ors_directions
from urllib.parse import urljoin
from operator import itemgetter
from typing import List, Optional, Tuple, Literal, TypeAlias
from pydantic import BaseModel, Field
#####################################################
# Map UI Integration
#####################################################
NWR: TypeAlias = Literal['node', 'way', 'relation']
POICategory: TypeAlias = Literal[
'Groceries', 'Recreation', 'Restaurants & Bars', 'Travel & Tourism',
'Healthcare', 'Education & Schools', 'Fuel & EV Charging',
'Religious Locations'
]
class OsmPOI(BaseModel):
"""Represents a Point of Interest found during map search."""
name: str = Field(description="Name of the Point of Interest.")
address: Optional[str] = Field(description="Address of the Point of Interest.")
description: str = Field(description=("Useful one sentence description of the Point of Interest, "
"containing important or unique information. "
"Do not put distance here."))
distance: float = Field(description="Distance in km or miles from the search location.")
distance_unit: Literal["km", "mi", "kilometers", "miles"] = Field(description="Unit of distance.")
lat: float = Field(description="Latitude of the Point of Interest.")
lon: float = Field(description="Longitude of the Point of Interest.")
osm_id: str = Field(description="OpenStreetMap ID of the Point of Interest.")
osm_type: NWR = Field(description="OpenStreetMap entity type of the Point of Interest.")
pass
MAP_UI = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="light dark">
<title>Search Results</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
color: #333;
line-height: 1.6;
padding: 12px;
min-height: 560px;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.results {
display: flex;
flex-wrap: wrap;
align-items: start;
justify-content: space-between;
}
@media (width <= 600px) {
.results {
flex-direction: column;
gap: 50px;
}
.map-container {
flex: auto;
min-width: 100%;
}
}
@media (width > 600px) {
.results {
flex-direction: row;
gap: 50px;
}
.map-container {
flex: auto;
}
}
h1 {
font-size: 2rem;
font-weight: 700;
color: #2c3e50;
text-align: center;
margin-bottom: 5px;
}
.subtitle {
font-size: 0.9rem;
color: #6c757d;
text-align: center;
margin-bottom: 15px;
}
h2 {
font-size: 1.3rem;
color: #34495e;
margin: 20px 0 10px;
font-weight: 600;
}
#map {
height: 400px;
margin-bottom: 15px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
border: 1px solid #ddd;
}
.poi-list-container {
flex: initial;
}
#poi-list {
list-style-type: none;
max-height: 400px;
overflow-y: auto;
}
#poi-list li {
padding: 10px 12px;
margin: 0;
background-color: white;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s ease;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
border: 1px solid #e9ecef;
font-weight: 600;
color: #495057;
display: flex;
flex-direction: column;
}
#poi-list li:hover {
transform: translateY(-2px);
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
background-color: #f8f9fa;
color: #2c3e50;
}
#poi-list li.active {
background-color: #3498db;
color: white;
box-shadow: 0 3px 8px rgba(52, 152, 219, 0.2);
}
.poi-description {
font-size: 0.8rem;
color: #555; /* Slightly lighter than default */
margin-top: 4px;
font-weight: 400;
}
.poi-distance {
font-size: 0.8rem;
color: #444; /* Slightly lighter than default */
margin-top: 4px;
font-weight: 400;
}
#poi-list li.active .poi-description {
color: rgba(255, 255, 255, 0.9); /* Lighter text for active state */
}
</style>
</head>
<body>
<div class="container" id="app">
<h1>Map Results for {REPLACE_WITH_CATEGORY}</h1>
<p class="subtitle">Data from OpenStreetMap</p>
<div class="results">
<div class="map-container">
<h2>Map</h2>
<div id="map"></div>
</div>
<div class="poi-list-container">
<h2>POI List</h2>
<ul id="poi-list"></ul>
</div>
</div>
</div>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
// POI data with coordinates and names
// [ { name, coords, lat, lon, description } ]
const poiData = {REPLACE_WITH_POI_RESULTS};
function getContentHeight() {
const app = document.getElementById('app');
if (!app) return 0;
return Math.ceil(app.getBoundingClientRect().height);
}
function notifyParentOfHeight() {
const height = getContentHeight();
if (!window.parent || height <= 0) return;
window.parent.postMessage(
{ type: 'iframe:height', height: height + 24 },
'*'
);
}
function scheduleHeightReport() {
requestAnimationFrame(() => notifyParentOfHeight());
setTimeout(notifyParentOfHeight, 100);
setTimeout(notifyParentOfHeight, 300);
}
// Function to create the map
function createMap(poiData) {
// Create map centered on first POI
const map = L.map('map', { minZoom: 3, maxZoom: 18 });
if (poiData.length > 0) {
map.setView([poiData[0].lat, poiData[0].lon], 12);
}
// Add OpenStreetMap tiles
L.tileLayer('{REPLACE_WITH_TILE_SERVER}', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
// Store markers and popup references
const markers = [];
// Add markers to map and create list items dynamically
poiData.forEach((poi, index) => {
const marker = L.marker([poi.lat, poi.lon]).addTo(map);
const osmLink = `https://www.openstreetmap.org/${poi.osm_type}/${poi.osm_id}`;
const header = `<h3><a target="_blank" href="${osmLink}">${poi.name}</a></h3>`;
const address = `<p>${poi.address ?? ''}</p>`;
const description = `<p>${poi.description}</p>`;
const coords = `<p>Coordinates: ${poi.lat.toFixed(4)}, ${poi.lon.toFixed(4)}</p>`;
const distance = `${poi.distance.toFixed(2)} ${poi.distance_unit}`;
marker.bindPopup(`${header}${address}${description}<p>${distance}</p>${coords}`);
marker.on('popupopen', scheduleHeightReport);
marker.on('popupclose', scheduleHeightReport);
markers.push(marker);
const listItem = document.createElement('li');
listItem.innerHTML = `
<span>${poi.name}</span>
<span class="poi-description">${poi.description}</span>
<span class="poi-distance">${distance}</span>`;
listItem.onclick = () => focusOnMarker(index, map, markers);
listItem.classList.add('poi-item');
document.getElementById('poi-list').appendChild(listItem);
});
return { map, markers };
}
// Function to focus on a specific marker
function focusOnMarker(index, map, markers) {
const marker = markers[index];
map.flyTo(marker.getLatLng(), 15);
marker.openPopup();
updateActiveListItem(index);
scheduleHeightReport();
}
// Function to update active list item
function updateActiveListItem(index) {
const listItems = document.querySelectorAll('#poi-list li');
listItems.forEach((item, i) => {
if (i === index) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
}
// Initialize map and markers
const { map, markers } = createMap(poiData);
// Initialize with first POI selected
if (poiData.length > 0) {
updateActiveListItem(0);
}
window.addEventListener('load', scheduleHeightReport);
window.addEventListener('resize', scheduleHeightReport);
map.whenReady(() => {
scheduleHeightReport();
setTimeout(() => {
map.invalidateSize();
scheduleHeightReport();
}, 100);
});
map.on('load zoomend moveend resize', scheduleHeightReport);
const app = document.getElementById('app');
if (app) {
const resizeObserver = new ResizeObserver(() => notifyParentOfHeight());
resizeObserver.observe(app);
}
</script>
</body>
</html>
"""
#####################################################
# Category Type Aliases
#####################################################
UrbanSetting: TypeAlias = Literal['urban', 'suburban', 'rural']
StoreCategory: TypeAlias = Literal[
'groceries', 'convenience', 'alcohol', 'drugs',
'cannabis', 'electronics', 'electrical', 'hardware', 'diy'
]
RecreationCategory: TypeAlias = Literal[
'swimming', 'playgrounds', 'amusement', 'sports', 'gyms'
]
EateryCategory: TypeAlias = Literal[
'sit_down_restaurants', 'fast_food', 'cafe_or_bakery',
'bars_and_pubs'
]
TravelCategory: TypeAlias = Literal[
'tourist_attractions', 'accommodation', 'bike_rentals',
'car_rentals', 'public_transport'
]
HealthcareCategory: TypeAlias = Literal[
'doctor', 'dentist', 'hospital', 'pharmacy'
]
EducationCategory: TypeAlias = Literal[
'schools', 'universities_and_colleges', 'libraries'
]
FuelCategory: TypeAlias = Literal['fossil_fuels', 'ev_fast_charging']
FuelTypeCategory: TypeAlias = Literal['petrol', 'diesel', 'all']
EVChargerCategory: TypeAlias = Literal[
'chademo', 'chademo3', 'chaoji', 'ccs2',
'ccs1', 'gb/t', 'nacs', 'all'
]
# Religions from the OSM wiki. Some make use of the denomination tag.
# Others do not. any_religion is a special "category" that forces the
# tool to search for any place of worship amenity.
ReligionCategory: TypeAlias = Literal[
'any_religion', 'buddhist', 'christian', 'hindu', 'jain', 'jewish', 'muslim',
'pagan', 'shinto', 'sikh', 'taoist', 'zoroastrian',
'ancestor', 'animist', 'antoinist', 'bahai', 'benzhu',
'caodaism', 'chinese_folk', 'confucian', 'shamanic', 'scientologist',
'self-realization_fellowship', 'spiritualist', 'tenrikyo',
'unitarian_universalist','vietnamese_folk', 'voodoo',
'yazidi',
'multifaith', 'humanist', 'atheist', 'null', 'laica'
]
DenominationCategory: TypeAlias = Literal[
# Forcibly search for any denomination within the specified
# religion.
'any_denomination',
# Buddhist
"buddhist|mahayana", "buddhist|gelug", "buddhist|jishu", "buddhist|jodo_shinshu",
"buddhist|jodo_shu", "buddhist|nichiren", "buddhist|nyingma", "buddhist|obaku",
"buddhist|pure_land", "buddhist|rinzai", "buddhist|risshu", "buddhist|shingon_shu",
"buddhist|soto", "buddhist|tiantai", "buddhist|tibetan","buddhist|vajrayana", "buddhist|won",
"buddhist|yogacara", "buddhist|yuzu_nembutsu", "buddhist|zen", "buddhist|theravada",
"buddhist|thai_mahanikaya", "buddhist|thai_thammayut",
# Christian
"christian|catholic", "christian|armenian_catholic", "christian|chaldean_catholic",
"christian|coptic_catholic", "christian|eritrean_catholic", "christian|ethiopian_catholic",
"christian|greek_catholic", "christian|hungarian_greek_catholic", "christian|maronite",
"christian|polish_catholic", "christian|roman_catholic", "christian|romanian_catholic",
"christian|syriac_catholic", "christian|syro-malabar_catholic", "christian|ukrainian_greek_catholic",
"christian|orthodox", "christian|antiochian_orthodox", "christian|armenian_apostolic",
"christian|bulgarian_orthodox", "christian|eritrean_orthodox", "christian|ethiopian_orthodox",
"christian|coptic_orthodox", "christian|georgian_orthodox", "christian|greek_orthodox",
"christian|macedonian_orthodox", "christian|old_believers", "christian|polish_orthodox",
"christian|romanian_orthodox", "christian|russian_orthodox", "christian|serbian_orthodox",
"christian|syriac_orthodox", "christian|ukrainian_orthodox", "christian|protestant",
"christian|adventist", "christian|anabaptist", "christian|anglican", "christian|baptist",
"christian|disciples_of_christ", "christian|episcopal", "christian|evangelical",
"christian|evangelical_covenant", "christian|exclusive_brethren", "christian|lutheran",
"christian|mennonite", "christian|methodist", "christian|moravian", "christian|pentecostal",
"christian|presbyterian", "christian|quaker", "christian|reformed", "christian|uniting",
"christian|polish_national_catholic", "christian|african_methodist_episcopal",
"christian|african_methodist_episcopal_zion", "christian|alliance", "christian|apostolic_faith",
"christian|assemblies_of_god", "christian|brethren_in_christ", "christian|calvinistic_methodist",
"christian|catholic_apostolic", "christian|church_of_god_in_christ", "christian|church_of_scotland",
"christian|churches_of_christ", "christian|czechoslovak_hussite", "christian|dutch_reformed",
"christian|evangelical_free_church_of_america", "christian|evangelical_lutheran",
"christian|evangelical_free_church_of_france", "christian|foursquare",
"christian|free_church_of_scotland", "christian|living_waters_church", "christian|mission_covenant_church_of_sweden",
"christian|mormon", "christian|nazarene", "christian|new_frontiers", "christian|orthodox_presbyterian_church",
"christian|pkn", "christian|remonstrant", "christian|salvation_army", "christian|scottish_episcopal",
"christian|seventh_day_adventist", "christian|strict_baptist", "christian|temple_society_australia",
"christian|united", "christian|united_free_church_of_scotland", "christian|united_reformed",
"christian|united_methodist", "christian|united_church_of_christ", "christian|welsh_baptist",
"christian|welsh_independent", "christian|apostolic", "christian|assyrian",
"christian|catholic_mariavite", "christian|bosnian_church", "christian|charismatic",
"christian|christian_community", "christian|christ_scientist", "christian|church_of_christ",
"christian|congregational", "christian|ecumenical", "christian|fsspx", "christian|harrist",
"christian|iglesia_ni_cristo", "christian|jehovahs_witness", "christian|kimbanguist",
"christian|la_luz_del_mundo", "christian|liberal_catholic", "christian|mariavite",
"christian|messianic_jewish", "christian|new_apostolic", "christian|nondenominational",
"christian|old_catholic", "christian|philippine_independent", "christian|shizmatic",
"christian|simultaneum", "christian|spiritist",
# Hindu
"hindu|shaktism", "hindu|hare_krishna", "hindu|vaishnavism", "hindu|shaivism",
"hindu|smartism", "hindu|ganpatya", "hindu|warkari", "hindu|dattatreya",
# Islamic
"muslim|ahmadiyya", "muslim|alevi", "muslim|bektashi", "muslim|ibadi",
"muslim|ismaili", "muslim|shia", "muslim|sunni", "muslim|sufi",
# Jain
"jain|digambara", "jain|svetambara",
# Jewish
"jewish|unaffiliated", "jewish|ashkenazi", "jewish|buchari",
"jewish|conservative", "jewish|hasidic", "jewish|kabbalistic",
"jewish|karaite", "jewish|lubavitch", "jewish|mizrachi",
"jewish|modern_orthodox", "jewish|neo_orthodox", "jewish|orthodox",
"jewish|reconstructionist", "jewish|reform", "jewish|progressive",
"jewish|liberal", "jewish|samaritan", "jewish|sephardi",
"jewish|traditional", "jewish|unity",
# Pagan
"pagan|asatru", "pagan|baltic", "pagan|celtic", "pagan|greco-roman",
"pagan|slavic", "pagan|wicca",
# Sikh
"sikh|khalsa", "sikh|akali_nihang", "sikh|giani_samparda", "sikh|nirmala_sect",
"sikh|sewapanthi", "sikh|udasi", "sikh|ramgarhia", "sikh|radha_soami",
"sikh|namdhari", "sikh|nirankari", "sikh|nanakpanthi", "sikh|ramraiyas",
# Taoist
"taoist|quanzhen", "taoist|zhengyi",
# Zoroastrian
"zoroastrian|irani", "zoroastrian|parsi",
]
#####################################################
# Citation CSS
#####################################################
# Yoinked from the OpenWebUI CSS
FONTS = ",".join([
"-apple-system", "BlinkMacSystemFont", "Inter",
"ui-sans-serif", "system-ui", "Segoe UI",
"Roboto", "Ubuntu", "Cantarell", "Noto Sans",
"sans-serif", "Helvetica Neue", "Arial",
"\"Apple Color Emoji\"", "\"Segoe UI Emoji\"",
"Segoe UI Symbol", "\"Noto Color Emoji\""
])
FONT_CSS = f"""
html {{ font-family: {FONTS}; }}
@media (prefers-color-scheme: dark) {{
html {{
--tw-text-opacity: 1;
color: rgb(227 227 227 / var(--tw-text-opacity));
}}
}}
"""
HIGHLIGHT_CSS = HtmlFormatter().get_style_defs('.highlight')
#####################################################
# Useful Constants
#####################################################
NOMINATIM_LOOKUP_TYPES = {
"node": "N",
"route": "R",
"way": "W"
}
OLD_VALVE_SETTING = """ Tell the user that you cannot search
OpenStreetMap until the configuration is fixed. The Nominatim URL
valve setting needs to be updated. There has been a breaking change in
1.0 of the OpenStreetMap tool. The valve setting is currently set to:
`{OLD}`.
It shoule be set to the root URL of the Nominatim endpoint, for
example:
`https://nominatim.openstreetmap.org/`
Inform the user they need to fix this configuration setting.
""".replace("\n", " ").strip()
VALVES_NOT_SET = {
"results": [],
"instructions": (
"Tell the user that the User-Agent and From headers"
"must be set to comply with the OSM Nominatim terms"
"of use: https://operations.osmfoundation.org/policies/nominatim/"
).replace("\n", " ").strip()
}
NO_RESULTS = {
"results": [],
"instructions": ("No results found. Tell the user you found no results. "
"Do not make up answers or hallucinate. Only say you "
"found no results.")
}
NO_RESULTS_BAD_ADDRESS = {
"results": [],
"instructions": ("No results found. Tell the user you found no results because "
"OpenStreetMap could not resolve the address. "
"Print the exact address or location you searched for. "
"Suggest to the user that they refine their "
"question, for example removing the apartment number, sub-unit, "
"etc. Example: If `123 Main Street, Apt 4` returned no results, "
"suggest that the user searc for `123 Main Street` instead. "
"Use the address the user searched for in your example.")
}
NO_CONFUSION = ("**IMPORTANT!:** Check that the results match the location "
"the user is talking about, by analyzing the conversation history. "
"Sometimes there are places with the same "
"names, but in different cities or countries. If the results are for "
"a different city or country than the user is interested in, say so: "
"tell the user that the results are for the wrong place, and tell them "
"to be more specific in their query.")
# Give examples of OSM links to help prevent wonky generated links
# with correct GPS coords but incorrect URLs.
EXAMPLE_OSM_LINK = "https://www.openstreetmap.org/#map=19/<lat>/<lon>"
OSM_LINK_INSTRUCTIONS = (
"When necessary, make friendly human-readable OpenStreetMap links "
"by using the latitude and longitude of the amenities: "
f"{EXAMPLE_OSM_LINK}\n\n"
)
CITATION_INSTRUCTIONS = [
(
"Always use inline citations in the format "
"[id], using the citation_id of each source."
),
(
"The citation ID must be in the form of [<citation_id>]. "
"For example, if the citation_id ID is 123456789, print [123456789]."
),
"Do NOT print [id:123456789]. That will not work. ",
"Always use inline citations for information relating to a result. "
]
#####################################################
# Global Utils
#####################################################
def chunk_list(input_list, chunk_size):
it = iter(input_list)
return list(
itertools.zip_longest(*[iter(it)] * chunk_size, fillvalue=None)
)
def to_lookup(thing) -> Optional[str]:
lookup_type = NOMINATIM_LOOKUP_TYPES.get(thing['type'])
if lookup_type is not None:
return f"{lookup_type}{thing['id']}"
def get_or_none(tags: dict, *keys: str) -> Optional[str]:
"""
Try to extract a value from a dict by trying keys in order, or
return None if none of the keys were found.
"""
for key in keys:
if key in tags:
return tags[key]
return None
def all_are_none(*args) -> bool:
for arg in args:
if arg is not None:
return False
return True
#####################################################
# Instruction Generation
#####################################################
def specific_place_instructions() -> str:
return (
"# Result Instructions\n"
"These are search results ordered by relevance for the "
"address, place, landmark, or location the user is asking "
"about. **IMPORTANT!:** Tell the user all relevant information, "
"including address, contact information, and the OpenStreetMap link. "
"Make the map link into a nice human-readable markdown link."
)
def navigation_instructions(travel_type) -> str:
return (
"This is the navigation route that the user has requested. "
f"These instructions are for travel by {travel_type}. "
"Tell the user the total distance, "
"and estimated travel time. "
"If the user **specifically asked for it**, also tell "
"them the route itself. When telling the route, you must tell "
f"the user that it's a **{travel_type}** route."
)
def list_instructions(tag_type: str, used_rel: bool) -> List[str]:
"""
Produce detailed instructions in a structured manner for
models that support it.
"""
instructions = {
"result_accuracy": [],
"information_reporting": [],
"links": [],
"citations": []
}
# basic instructions
if used_rel:
instructions["result_accuracy"].append(
"You **MUST** Begin your reply by explaining to the user "
"that we could not search the entire area, "
"and therefore we did not get all results."
)
instructions["result_accuracy"].append(
"Inform the user that more accurate results can be found by "
"using more specific search terms like a street or specific landmark."
)
else:
instructions["result_accuracy"].append("These are the results known to be closest to the requested location.")
instructions["result_accuracy"].append("When saying the location name, use the resolved_location field.")
# how to report information
instructions["information_reporting"].append(
"When telling the user about the results, make sure to report "
"all information relevant to the user's query (address, contact info, website, etc)."
)
instructions["information_reporting"].append(
"Do not report information that is irrelvant to the user's query."
)
instructions["information_reporting"].append(
"Prefer closer results by TRAVEL DISTANCE first. "
"Closer results are higher in the list."
)
instructions["information_reporting"].append(
"When telling the user the distance, use the TRAVEL DISTANCE. Do not say one "
"distance is farther away than another. Just say what the distances are. "
)
instructions["information_reporting"].append(
"Only use relevant results. If there are no relevant results, "
"say so. Do not make up answers or hallucinate. "
)
instructions["information_reporting"].append(NO_CONFUSION)
instructions["information_reporting"].append(
"Remember that the CLOSEST result is first, and you should use "
"that result first."
)
# links and citations
instructions["links"].append(OSM_LINK_INSTRUCTIONS)
instructions["links"].append(
"Give map links friendly, contextual labels. "
"Don't just print the naked link. "
f"Example: `You can view it on [OpenStreetMap]({EXAMPLE_OSM_LINK})`"
)
instructions["citations"].extend(CITATION_INSTRUCTIONS)
return instructions
def simple_instructions(tag_type_str: str, used_rel: bool) -> str:
"""
Produce simpler markdown-oriented instructions for models that do
better with that.
"""
if used_rel:
rel_inst = (
"**Mention that the central point of the town or city that the user is searching in "
"was used, and that results may not cover the whole area.**"
)
else:
rel_inst = ""
return (
f"These are some of the {tag_type_str} points of interest nearby. "
"These are the results known to be closest to the requested location. "
"For each result, report the following information: \n"
" - Name\n"
" - Address\n"
" - OpenStreetMap Link (make it a human readable link like 'View on OpenStreetMap')\n"
" - Contact information (address, phone, website, email, etc)\n\n"
"Use the information provided to answer the user's question. "
"The results are ordered by closeness as the crow flies. "
"When telling the user about distances, use the TRAVEL DISTANCE only. "
"Only use relevant results. If there are no relevant results, "
"say so. Do not make up answers or hallucinate. "
"Make sure that your results are in the actual location the user is talking about, "
"and not a place of the same name in a different country."
f"{rel_inst}"
)
#####################################################
# Event Emission
#####################################################
class OsmEventEmitter:
def __init__(self, event_emitter, status_indicators=True):
self.event_emitter = event_emitter
self.status_indicators = status_indicators
async def navigating(self, done: bool):
if not self.status_indicators:
return
if done:
message = "Navigation complete"
else:
message = "Navigating..."
await self.event_emitter({
"type": "status",
"data": {
"status": "in_progress",
"description": message,
"done": done,
},
})
async def navigation_error(self, exception: Exception):
if not self.status_indicators:
return
await self.event_emitter({
"type": "status",
"data": {
"status": "error",
"description": f"Error navigating: {str(exception)}",
"done": True,
},
})
async def resolving(self, done: bool=False, message: Optional[str]=None, items=[]):
if not self.status_indicators:
return
items = [
{
"title": get_or_none(item, "display_name"),
"link": OsmUtils.create_osm_link(item.get('lat', -1), item.get('lon', -1))
}
for item in items
]
if done:
message = "Resolution complete"
else:
message = f" location: {message}" if message is not None else "..."
message = f"Resolving{message}"
await self.event_emitter({
"type": "status",
"data": {
"action": "web_search",
"status": "in_progress",
"items": items if items else None,
"description": message,
"done": done,
},
})
async def searching(
self, category: str, place: str,
status: str="in_progress", done: bool=False,
tags=[]
):
if not self.status_indicators:
return
query = f"{category.capitalize()} POIs near {place}"
await self.event_emitter({
"type": "status",
"data": {
"status": status,
"action": "web_search_queries_generated",
"queries": [query],
"description": f"Searching for {category} near {place}",
"done": done,
},
})
async def search_complete(self, category: str, place: str, items=[]):
if not self.status_indicators:
return
num_results = len(items)
citation_items = []
for item in items:
name = get_or_none(item.get('tags', {}), "name", "brand")
addr = get_or_none(item.get('tags', {}), "addr:street", "addr:city")
addr = f"({addr})" if addr else ""
title = f"{name} {addr}".strip()
osm_link = OsmUtils.create_osm_link(item.get('lat', -1), item.get('lon', -1))
citation_items.append({
"title": title,
"link": osm_link
})
await self.event_emitter({
"type": "status",
"data": {
"action": "web_search",
"status": "in_progress",
"items": citation_items if citation_items else None,
"description": f"Found {num_results} results for {category}",
"done": True,
},
})
await self.event_emitter({
"type": "status",
"data": {
"action": "sources_retrieved",
"status": "in_progress",
"count": num_results,
"description": f"Found {num_results} results for {category}",
"done": True,
},
})
async def emit_result_citation(self, thing):
if not self.status_indicators:
return
converted = OsmUtils.create_citation_document(thing)
if not converted:
return
source_name = converted["source_name"]
document = converted["document"]
osm_link = converted["osm_link"]
website = converted["website"]
await self.event_emitter({
"type": "source",
"data": {
"document": [document],
"metadata": [{"source": source_name, "html": True }],
"source": {"name": website, "url": website},
}
})
async def error(self, exception: Exception):
if not self.status_indicators:
return
await self.event_emitter({
"type": "status",
"data": {
"status": "error",
"description": f"Error searching OpenStreetMap: {str(exception)}",
"done": True,
},
})
#####################################################
# OSM-Related Utility Functions (AKA spaghetti land)
#####################################################
class OsmUtils:
"""
Utility functions that are organized as static methods. AKA
dumping ground for spaghetti code.
"""
@staticmethod
def create_citation_document(thing) -> Optional[dict]:
if not thing:
return None
if 'address' in thing:
street = get_or_none(thing['address'], "road")
else:
street = get_or_none(thing['tags'], "addr:street")
id = thing.get('id', None)
street_name = street if street is not None else ""
source_name = f"{thing['name']} {street_name}"
lat, lon = thing['lat'], thing['lon']
addr = f"at {thing['address']}" if thing['address'] != 'unknown' else 'nearby'
osm_link = OsmUtils.create_osm_link(lat, lon)
json_data = OsmUtils.pretty_print_thing_json(thing)
website = thing.get('website', osm_link)
document = (f"<style>{HIGHLIGHT_CSS}</style>"
f"<style>{FONT_CSS}</style>"
f"<div>"
f"<p>{thing['name']} is located {addr}.</p>"
f"<ul>"
f"<li>"
f" <strong>Opening Hours:</strong> {thing['opening_hours']}"
f"</li>"
f"</ul>"
f"<p>Raw JSON data:</p>"
f"{json_data}"
f"</div>")
return {
"id": id,
"source_name": source_name,
"document": document,
"osm_link": osm_link,
"website": website
}
@staticmethod
def create_osm_link(lat, lon):
return EXAMPLE_OSM_LINK.replace("<lat>", str(lat)).replace("<lon>", str(lon))
@staticmethod
def pretty_print_thing_json(thing):
"""Converts an OSM thing to nice JSON HTML."""
formatted_json_str = json.dumps(thing, indent=2)
lexer = JsonLexer()
formatter = HtmlFormatter(style='colorful')
return highlight(formatted_json_str, lexer, formatter)
@staticmethod
def thing_is_useful(thing):
"""
Determine if an OSM way entry is useful to us. This means it
has something more than just its main classification tag, and
(usually) has at least a name. Some exceptions are made for ways
that do not have names.
"""