-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathufojson.cpp
3466 lines (2756 loc) · 125 KB
/
ufojson.cpp
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
// ufojson.cpp
// Copyright (C) 2023 Richard Geldreich, Jr.
#include "utils.h"
#include "markdown_proc.h"
#include "ufojson_core.h"
#include "udb.h"
#include "converters.h"
#include "utf8.h"
//-------------------------------------------------------------------
static void detect_bad_urls()
{
string_vec unique_urls;
bool utf8_flag = false;
if (!read_text_file("unique_urls.txt", unique_urls, true, &utf8_flag))
panic("Can't read file unique_urls.txt");
uint32_t total_processed = 0;
string_vec failed_urls;
for (const auto& url : unique_urls)
{
printf("-------------- URL : %u\n", total_processed);
string_vec reply;
bool status = invoke_curl(url, reply);
bool not_found = false;
if (status)
{
for (auto str : reply)
{
str = string_lower(str);
if ((string_find_first(str, "404 not found") != -1) ||
(string_find_first(str, "cannot find the requested page") != -1))
{
not_found = true;
break;
}
}
}
if ((!status) || (not_found))
{
failed_urls.push_back(url);
printf("FAILED: %s\n", url.c_str());
}
else
{
printf("SUCCEEDED: %s\n", url.c_str());
}
total_processed++;
if ((total_processed % 25) == 24)
{
if (!write_text_file("failed_urls.txt", failed_urls, false))
panic("Unable to create file failed_urs.txt");
}
}
printf("Total urls: %zu, failed: %zu\n", unique_urls.size(), failed_urls.size());
if (!write_text_file("failed_urls.txt", failed_urls, false))
panic("Unable to create file failed_urs.txt");
}
// Windows defaults to code page 437:
// https://www.ascii-codes.com/
// We want code page 1252
// http://www.alanwood.net/demos/ansi.html
static bool invoke_openai(const char* pPrompt_text, json& result)
{
uprintf("Prompt: %s\n", pPrompt_text);
std::string res_str;
const uint32_t MAX_TRIES = 3;
for (uint32_t try_index = 0; try_index < MAX_TRIES; try_index++)
{
bool status = invoke_openai(pPrompt_text, res_str);
if (status)
break;
if (try_index == MAX_TRIES - 1)
{
fprintf(stderr, "invoke_openai() failed!\n");
return false;
}
}
uprintf("Result: %s\n", res_str.c_str());
bool success = false;
try
{
result = json::parse(res_str.begin(), res_str.end());
success = true;
}
catch (json::exception& e)
{
fprintf(stderr, "json::parse() failed (id %i): %s", e.id, e.what());
return false;
}
if (!result.is_object() || !result.size())
{
fprintf(stderr, "Invalid JSON!\n");
return false;
}
return true;
}
static bool invoke_openai(const timeline_event &event, const char *pPrompt_text, json& result)
{
markdown_text_processor tp;
tp.init_from_markdown(event.m_desc.c_str());
std::string desc;
tp.convert_to_plain(desc, true);
if ((desc.size() >= 2) && (desc.back() == '('))
desc.pop_back();
const uint32_t MAX_SIZE = 4096; // ~1024 tokens
if (desc.size() > MAX_SIZE)
{
int i;
for (i = MAX_SIZE; i >= 0; i--)
{
if (desc[i] == ' ')
{
desc.resize(i);
break;
}
}
if (i < 0)
panic("Failed shrinking text");
}
uprintf("Desc: %s\n\n", desc.c_str());
std::string prompt_str(pPrompt_text);
prompt_str += desc;
prompt_str += "\"";
return invoke_openai(prompt_str.c_str(), result);
}
static void process_timeline_using_openai(const ufo_timeline &timeline)
{
bool utf8_flag;
json existing_results;
load_json_object("openai_results.json", utf8_flag, existing_results);
json final_result = json::object();
final_result["results"] = json::array();
auto& results_array = final_result["results"];
uint32_t total_failures = 0, total_hits = 0, total_new_results = 0;
for (uint32_t i = 0; i < timeline.size(); i++)
//for (uint32_t i = 8515; i < 8516; i++)
{
uprintf("****** Record: %u\n", i);
const timeline_event& event = timeline[i];
const uint32_t event_crc32 = event.get_crc32();
json result_obj;
bool found_flag = false;
if (existing_results.is_object() && existing_results.size())
{
const auto& results_arr = existing_results["results"];
for (auto it = results_arr.begin(); it != results_arr.end(); ++it)
{
const auto& obj = *it;
if (obj.is_object())
{
uint32_t peek_obj_crc32 = obj["event_crc32"].get<uint32_t>();
if (peek_obj_crc32 == event_crc32)
{
if (obj["event_source_id"] == event.m_source_id)
{
result_obj = obj;
found_flag = true;
break;
}
}
}
}
}
if (found_flag)
{
total_hits++;
printf("Found hit for record %u\n", i);
results_array.push_back(result_obj);
continue;
}
if (!invoke_openai(event,
//"Compose a JSON object from the following quoted text. Give an array (with the key \"locations\") containing all the geographic locations or addresses. Then an array (with the key \"index\") with all phrases that would appear in a book index. Then an array (with the key \"names\") with all the person names. \"",
"Compose a JSON object from the following quoted text. Give an array (with the key \"locations\") containing all the geographic locations or addresses. Then an array (with the key \"index\") with all phrases that would appear in a book index. Then an array (with the key \"names\") with all the person names. For the locations, aggressively provide as few strings as possible so they can be geocoded. For example, if the input has \"County Waterford in Cappoquin, Ireland\", provide \"County Waterford, Cappoquin, Ireland\". \"",
result_obj))
{
fprintf(stderr, "Invoke AI failed!");
total_failures++;
continue;
}
result_obj["event_index"] = i;
result_obj["event_date_str"] = event.m_date_str;
if (event.m_time_str.size())
result_obj["event_time"] = event.m_time_str;
result_obj["event_source"] = event.m_source;
result_obj["event_source_id"] = event.m_source_id;
result_obj["event_crc32"] = event_crc32;
results_array.push_back(result_obj);
total_new_results++;
if ((total_new_results % 50) == 0)
{
serialize_to_json_file("temp_results.json", final_result, true);
}
}
if (!results_array.size())
panic("No results");
if (!serialize_to_json_file("new_openai_results.json", final_result, true))
panic("failed writing results.json");
uprintf("Total hits: %u, new results: %u, failures: %u\n", total_hits, total_new_results, total_failures);
uprintf("Success\n");
}
static void process_timeline_using_python(const ufo_timeline& timeline)
{
json final_result = json::object();
final_result["results"] = json::array();
auto& results_array = final_result["results"];
for (uint32_t i = 0; i < timeline.size(); i++)
//for (uint32_t i = 0; i < 5; i++)
{
uprintf("****** Record: %u\n", i);
const timeline_event& event = timeline[i];
string_vec lines;
lines.push_back(event.m_desc);
if (!write_text_file("input.txt", lines))
panic("Failed writing input.txt");
remove("locations.json");
Sleep(50);
int status = system("python.exe pextractlocs.py");
if (status != EXIT_SUCCESS)
panic("Failed running python.exe");
json locs;
bool utf8_flag;
if (!load_json_object("locations.json", utf8_flag, locs))
{
Sleep(50);
if (!load_json_object("locations.json", utf8_flag, locs))
panic("failed reading locations.json");
}
for (auto it = locs.begin(); it != locs.end(); ++it)
{
if (it->is_string())
uprintf("%s\n", it->get<std::string>().c_str());
}
json new_obj = json::object();
new_obj.emplace("index", i);
new_obj.emplace("date", event.m_date_str);
new_obj.emplace("crc32", event.get_crc32());
new_obj.emplace("locations", locs);
results_array.push_back(new_obj);
}
if (!results_array.size())
panic("No results");
if (!serialize_to_json_file("new_results.json", final_result, true))
panic("failed writing results.json");
}
enum
{
gn_geonameid, // integer id of record in geonames database
gn_name, // name of geographical point(utf8) varchar(200)
gn_asciiname, // name of geographical point in plain ascii characters, varchar(200)
gn_alternatenames, // alternatenames, comma separated, ascii names automatically transliterated, convenience attribute from alternatename table, varchar(10000)
gn_latitude, // latitude in decimal degrees(wgs84)
gn_longitude, // longitude in decimal degrees(wgs84)
gn_feature_class, // see http ://www.geonames.org/export/codes.html, char(1)
gn_feature_code, // see http ://www.geonames.org/export/codes.html, varchar(10)
gn_country_code, // ISO - 3166 2 - letter country code, 2 characters
gn_cc2, // alternate country codes, comma separated, ISO - 3166 2 - letter country code, 200 characters
gn_admin1_code, // fipscode(subject to change to iso code), see exceptions below, see file admin1Codes.txt for display names of this code; varchar(20)
gn_admin2_code, // code for the second administrative division, a county in the US, see file admin2Codes.txt; varchar(80)
gn_admin3_code, // code for third level administrative division, varchar(20)
gn_admin4_code, // code for fourth level administrative division, varchar(20)
gn_population, // bigint(8 byte int)
gn_elevation, // in meters, integer
gn_dem, // digital elevation model, srtm3 or gtopo30, average elevation of 3''x3'' (ca 90mx90m) or 30''x30'' (ca 900mx900m) area in meters, integer.srtm processed by cgiar / ciat.
gn_timezone, // the iana timezone id(see file timeZone.txt) varchar(40)
gn_modification_date,
gn_total
};
struct geoname
{
std::string m_fields[gn_total];
};
typedef std::vector<geoname> geoname_vec;
static bool is_important_country(const std::string& s)
{
return (s == "US") || (s == "GB") || (s == "AU") || (s == "CA") || (s == "NZ") || (s == "FR") || (s == "DE") || (s == "BR") || (s == "IT");
}
static bool is_favored_country(const std::string& s)
{
return (s == "US") || (s == "GB") || (s == "AU") || (s == "CA") || (s == "NZ") || (s == "FR") || (s == "DE");
}
const uint32_t TOTAL_FAVORED_COUNTRY_RANKS = 8;
static int get_favored_country_rank(const std::string& s)
{
if (s == "US")
return 0;
else if (s == "CA")
return 1;
else if (s == "GB")
return 2;
else if (s == "AU")
return 3;
else if (s == "NZ")
return 4;
else if (s == "FR")
return 5;
else if (s == "DE")
return 6;
return 7;
}
static bool is_country_fcode(const std::string &fcode)
{
return ((fcode == "PCL") || (fcode == "PCLD") || (fcode == "PCLF") || (fcode == "PCLH") || (fcode == "PCLI") || (fcode == "PCLIX") || (fcode == "PCLS") || (fcode == "TERR"));
}
static void process_geodata()
{
string_vec lines;
lines.reserve(13000000);
if (!read_text_file("allCountries.txt", lines, true, nullptr))
panic("failed reading allCountries.txt");
int_vec tab_locs;
tab_locs.reserve(32);
geoname_vec geonames;
geonames.resize(13000000);
uint32_t total_geonames = 0;
uint32_t max_col_sizes[gn_total];
clear_obj(max_col_sizes);
std::unordered_map<char, uint32_t> accepted_class_counts;
std::unordered_map<char, uint32_t> rejected_class_counts;
uint32_t total_accepted = 0;
json output_json = json::array();
for (const auto& str : lines)
{
tab_locs.resize(0);
for (uint32_t ofs = 0; ofs < str.size(); ofs++)
if (str[ofs] == '\t')
tab_locs.push_back(ofs);
if (tab_locs.size() != 18)
panic("Unexpected number of tabs");
tab_locs.push_back((uint32_t)str.size());
geoname& g = geonames[total_geonames];
uint32_t cur_ofs = 0;
for (uint32_t i = 0; i < gn_total; i++)
{
g.m_fields[i] = string_slice(str, cur_ofs, tab_locs[i] - cur_ofs);
#if 0
const uint32_t MAX_ALT_NAMES_SIZE = 1024;
if ((i == gn_alternatenames) && (g.m_fields[i].size() > MAX_ALT_NAMES_SIZE))
{
int j;
for (j = MAX_ALT_NAMES_SIZE; j >= 0; j--)
{
if (g.m_fields[i][j] == ',')
{
g.m_fields[i].resize(j);
break;
}
}
if (j < 0)
g.m_fields[i].resize(0);
}
#endif
max_col_sizes[i] = std::max(max_col_sizes[i], (uint32_t)g.m_fields[i].size());
cur_ofs = tab_locs[i] + 1;
}
bool accept_flag = false;
bool has_min_pop = false;
if (g.m_fields[gn_population].size())
{
int pop = atoi(g.m_fields[gn_population].c_str());
const int MIN_POP = 10;
if (pop >= MIN_POP)
has_min_pop = true;
}
const auto& code = g.m_fields[gn_feature_code];
char feature_class = ' ';
if (g.m_fields[gn_feature_class].size() == 1)
feature_class = g.m_fields[gn_feature_class][0];
switch (feature_class)
{
case 'T': // mountain,hill,rock,...
if ((code == "MT") || (code == "MTS") || (code == "ATOL") || (code == "CAPE") || (code == "CNYN") || (code == "DSRT") ||
(code == "ISL") || (code == "ISLS") || (code == "PEN") || (code == "VALS") || (code == "VALX"))
{
accept_flag = true;
}
break;
case 'S': // spot, building, farm
if ((code == "AIRB") || (code == "AIRF") || (code == "AIRP") || (code == "AIRQ") || (code == "BRKS") || (code == "CTRA") ||
(code == "CTRS") || (code == "INSM") || (code == "ITTR") || (code == "PSN") || (code == "STNE") || (code == "USGE") ||
(code == "OBS") || (code == "OBSR") || (code == "MFGM") || (code == "FT") || (code == "ASTR") || (code == "FCL") ||
(code == "PS") || (code == "PSH") || (code == "STNB") || (code == "STNS") || (code == "UNIV"))
{
accept_flag = true;
}
break;
case 'L': // parks,area, ...
if ((code == "MILB") || (code == "MVA") || (code == "NVB") || (code == "BTL") || (code == "CST") || (code == "RNGA") || (code == "PRK") || (code == "RESV"))
{
accept_flag = true;
}
break;
case 'A': // country, state, region,...
accept_flag = true;
//accept_flag = has_min_pop;
break;
case 'H': // stream, lake, ...
if ((code == "BAY") || (code == "BAYS") || (code == "CHN") || (code == "CHNL") || (code == "CHNM") || (code == "CHNN") ||
(code == "CNL") || (code == "CNL") || (code == "LK") || (code == "LKN") || (code == "LKS") || (code == "RSV") || (code == "SD") || (code == "STRT"))
{
accept_flag = true;
}
break;
case 'P': // city, village,...
if ((code == "PPLC") || (code == "PPLG") || (code == "PPLA")) // TODO
accept_flag = true;
else if (is_important_country(g.m_fields[gn_country_code]))
accept_flag = true;
else
accept_flag = has_min_pop;
break;
case 'R': // road, railroad
break;
case 'U': // undersea
break;
case 'V': // forest,heath,...
break;
default:
break;
}
if (accept_flag)
{
accepted_class_counts[feature_class] = accepted_class_counts[feature_class] + 1;
json obj = json::object();
obj["id"] = g.m_fields[gn_geonameid].size() ? atoi(g.m_fields[gn_geonameid].c_str()) : -1;
obj["name"] = g.m_fields[gn_name];
obj["plainname"] = g.m_fields[gn_asciiname];
if (g.m_fields[gn_alternatenames].size())
obj["altnames"] = g.m_fields[gn_alternatenames];
if (g.m_fields[gn_feature_class].size())
obj["fclass"] = g.m_fields[gn_feature_class];
if (g.m_fields[gn_feature_code].size())
obj["fcode"] = g.m_fields[gn_feature_code];
if (g.m_fields[gn_country_code].size())
obj["ccode"] = g.m_fields[gn_country_code];
if (g.m_fields[gn_cc2].size())
obj["cc2"] = g.m_fields[gn_cc2];
if (g.m_fields[gn_admin1_code].size())
obj["a1"] = g.m_fields[gn_admin1_code];
if (g.m_fields[gn_admin2_code].size())
obj["a2"] = g.m_fields[gn_admin2_code];
if (g.m_fields[gn_admin3_code].size())
obj["a3"] = g.m_fields[gn_admin3_code];
if (g.m_fields[gn_admin4_code].size())
obj["a4"] = g.m_fields[gn_admin4_code];
obj["lat"] = g.m_fields[gn_latitude].size() ? atof(g.m_fields[gn_latitude].c_str()) : 0.0f;
obj["long"] = g.m_fields[gn_longitude].size() ? atof(g.m_fields[gn_longitude].c_str()) : 0.0f;
if (g.m_fields[gn_population].size())
obj["pop"] = atoi(g.m_fields[gn_population].c_str());
output_json.push_back(obj);
total_accepted++;
if ((total_accepted % 1000) == 0)
uprintf("Total accepted: %u\n", total_accepted);
}
else
{
rejected_class_counts[feature_class] = rejected_class_counts[feature_class] + 1;
}
total_geonames++;
if ((total_geonames % 1000000) == 0)
uprintf("Geonames processed: %u\n", total_geonames);
}
if (!serialize_to_json_file("world_features.json", output_json, true))
panic("failed writing to file world_features.json");
uprintf("Total accepted: %u\n", total_accepted);
for (uint32_t i = 0; i < gn_total; i++)
uprintf("%u\n", max_col_sizes[i]);
uprintf("Accepted:\n");
for (const auto& s : accepted_class_counts)
uprintf("%c %u\n", s.first, s.second);
uprintf("Rejected:\n");
for (const auto& s : rejected_class_counts)
uprintf("%c %u\n", s.first, s.second);
}
static const struct
{
const char* m_pCode;
int m_level;
} g_geocode_levels[] =
{
{ "ADM1", 1 },
{ "ADM1H", 1 },
{ "ADM2", 2 },
{ "ADM2H", 2 },
{ "ADM3", 3 },
{ "ADM3H", 3 },
{ "ADM4", 4 },
{ "ADM4H", 4 },
{ "ADM5", 5 },
{ "ADM5H", 5 },
{ "ADMD", 1 },
{ "ADMDH", 1 },
{ "PCL", 0 },
{ "PCLD", 0 },
{ "PCLF", 0 },
{ "PCLH", 0 },
{ "PCLI", 0 },
{ "PCLIX", 0 },
{ "PCLS", 0 },
{ "PRSH", 0 },
{ "TERR", 0 },
{ "ZN", 0 },
{ "ZNB", 0 }
};
const int MIN_GEOCODE_LEVEL = 0, MAX_GEOCODE_LEVEL = 5, NUM_GEOCODE_LEVELS = 6;
static int find_geocode_admin_level(const char* pCode)
{
for (const auto& l : g_geocode_levels)
if (_stricmp(pCode, l.m_pCode) == 0)
return l.m_level;
return -1;
}
struct country_info
{
std::string m_iso2_name;
std::string m_iso3_name;
std::string m_iso_numeric;
std::string m_fips;
std::string m_country_name;
std::string m_capital_name;
int m_area;
int m_pop;
std::string m_continent;
int m_geoid;
int m_rec_index;
std::string m_neighbors;
int m_pop_rank;
};
typedef std::vector<country_info> country_info_vec;
static int get_admin_level(const std::string& code)
{
if (code == "ADM1")
return 1;
else if (code == "ADM2")
return 2;
else if (code == "ADM3")
return 3;
else if (code == "ADM4")
return 4;
else if (code == "ADM5")
return 5;
if (code == "ADM1H")
return 1;
else if (code == "ADM2H")
return 2;
else if (code == "ADM3H")
return 3;
else if (code == "ADM4H")
return 4;
else if (code == "ADM5H")
return 5;
return 0;
}
class geodata
{
enum { HASH_BITS = 23U, HASH_SHIFT = 32U - HASH_BITS, HASH_FMAGIC = 2654435769U, MAX_EXPECTED_RECS = 3000000 };
public:
geodata()
{
assert((1U << HASH_BITS) >= MAX_EXPECTED_RECS * 2U);
}
void init()
{
uprintf("Reading hierarchy\n");
load_hierarchy();
uprintf("Reading world_features.json\n");
if (!read_text_file("world_features.json", m_filebuf, nullptr))
panic("Failed reading file");
uprintf("Deserializing JSON file\n");
bool status = m_doc.deserialize_in_place((char*)&m_filebuf[0]);
if (!status)
panic("Failed parsing JSON document!");
if (!m_doc.is_array())
panic("Invalid JSON");
uprintf("Hashing JSON data\n");
m_name_hashtab.resize(0);
m_name_hashtab.resize(1U << HASH_BITS);
const auto& root_arr = m_doc.get_array();
//crnlib::timer tm;
//tm.start();
uint8_vec name_buf;
m_geoid_to_rec.clear();
m_geoid_to_rec.reserve(MAX_EXPECTED_RECS);
for (uint32_t rec_index = 0; rec_index < root_arr.size(); rec_index++)
{
const auto& arr_entry = root_arr[rec_index];
if (!arr_entry.is_object())
panic("Invalid JSON");
int geoid = arr_entry.find_int32("id");
assert(geoid > 0);
auto ins_res = m_geoid_to_rec.insert(std::make_pair(geoid, (int)rec_index));
if (!ins_res.second)
panic("Invalid id!");
const auto pName = arr_entry.find_value_variant("name");
const auto pAltName = arr_entry.find_value_variant("altnames");
if ((pName == nullptr) || (!pName->is_string()))
panic("Missing/invalid name field");
{
const char* pName_str = pName->get_string_ptr();
size_t name_size = strlen(pName_str);
if (name_size > name_buf.size())
name_buf.resize(name_size);
for (uint32_t ofs = 0; ofs < name_size; ofs++)
name_buf[ofs] = utolower(pName_str[ofs]);
uint32_t hash_val = (hash_hsieh(&name_buf[0], name_size) * HASH_FMAGIC) >> HASH_SHIFT;
m_name_hashtab[hash_val].push_back(rec_index);
}
const auto pPlainName = arr_entry.find_value_variant("plainname");
if ((pPlainName == nullptr) || (!pPlainName->is_string()))
panic("Missing/invalid plainname field");
{
const char* pName_str = pPlainName->get_string_ptr();
size_t name_size = strlen(pName_str);
if (name_size > name_buf.size())
name_buf.resize(name_size);
for (uint32_t ofs = 0; ofs < name_size; ofs++)
name_buf[ofs] = utolower(pName_str[ofs]);
uint32_t hash_val = (hash_hsieh(&name_buf[0], name_size) * HASH_FMAGIC) >> HASH_SHIFT;
m_name_hashtab[hash_val].push_back(rec_index);
}
if (pAltName)
{
if (!pAltName->is_string())
panic("Missing/invalid altname field");
const char* pAlt_name_str = pAltName->get_string_ptr();
size_t alt_name_size = strlen(pAlt_name_str);
if (alt_name_size > name_buf.size())
name_buf.resize(alt_name_size);
for (uint32_t ofs = 0; ofs < alt_name_size; ofs++)
name_buf[ofs] = utolower(pAlt_name_str[ofs]);
uint32_t start_ofs = 0;
for (uint32_t i = 0; i < alt_name_size; i++)
{
if (pAlt_name_str[i] == ',')
{
size_t size = i - start_ofs;
assert(size);
uint32_t hash_val = (hash_hsieh(&name_buf[0] + start_ofs, size) * HASH_FMAGIC) >> HASH_SHIFT;
m_name_hashtab[hash_val].push_back(rec_index);
start_ofs = i + 1;
}
}
size_t size = alt_name_size - start_ofs;
assert(size);
uint32_t hash_val = (hash_hsieh(&name_buf[0] + start_ofs, size) * HASH_FMAGIC) >> HASH_SHIFT;
m_name_hashtab[hash_val].push_back(rec_index);
}
std::string fclass = arr_entry.find_string_obj("fclass");
if (fclass == "A")
{
std::string fcode(arr_entry.find_string_obj("fcode"));
if ((fcode == "ADM1") || (fcode == "ADM2") || (fcode == "ADM3") || (fcode == "ADM4"))
{
std::string ccode(arr_entry.find_string_obj("ccode"));
std::string a[4] = {
arr_entry.find_string_obj("a1"),
arr_entry.find_string_obj("a2"),
arr_entry.find_string_obj("a3"),
arr_entry.find_string_obj("a4") };
std::string desc(ccode);
for (uint32_t i = 0; i < 4; i++)
{
if (!a[i].size())
break;
desc += "." + a[i];
}
m_admin_map[desc].push_back(std::pair<int, int>(rec_index, get_admin_level(fcode)));
}
}
}
#if 0
if (m_admin_map.count(desc))
{
const int alt_admin_level = get_admin_level(fcode);
const int cur_rec_index = m_admin_map.find(desc)->second;
const pjson::value_variant* pCur = &m_doc[cur_rec_index];
const int cur_admin_level = get_admin_level(pCur->find_string_obj("fcode"));
if (alt_admin_level < cur_admin_level)
m_admin_map[desc] = rec_index;
else if (alt_admin_level == cur_admin_level)
{
uprintf("ccode: %s rec: %u geoid: %u name: %s fcode: %s, current rec: %u geoid: %u name: %s fcode: %s\n",
ccode.c_str(),
rec_index, geoid, pName->get_string_ptr(), fcode.c_str(),
cur_rec_index, pCur->find_int32("id"), pCur->find_string_obj("name").c_str(), pCur->find_string_obj("fcode").c_str());
}
}
else
#endif
for (auto it = m_admin_map.begin(); it != m_admin_map.end(); it++)
{
std::vector< std::pair<int, int> >& recs = it->second;
std::sort(recs.begin(), recs.end(),
[](const std::pair<int, int>& a, const std::pair<int, int>& b) -> bool
{
return a.second < b.second;
});
#if 0
uprintf("%s:\n", it->first.c_str());
for (uint32_t i = 0; i < recs.size(); i++)
{
const int cur_rec_index = recs[i].first;
const pjson::value_variant* pCur = &m_doc[cur_rec_index];
uprintf("admlevel: %u, rec: %u geoid: %u name: %s fcode: %s\n",
recs[i].second,
cur_rec_index, pCur->find_int32("id"), pCur->find_string_obj("name").c_str(), pCur->find_string_obj("fcode").c_str());
}
#endif
}
for (uint32_t i = 0; i < m_name_hashtab.size(); i++)
{
if (!m_name_hashtab[i].size())
continue;
std::sort(m_name_hashtab[i].begin(), m_name_hashtab[i].end());
auto new_end = std::unique(m_name_hashtab[i].begin(), m_name_hashtab[i].end());
m_name_hashtab[i].resize(new_end - m_name_hashtab[i].begin());
}
load_country_info();
//uprintf("geodata::init: Elapsed time: %f\n", tm.get_elapsed_secs());
}
void find(const char* pKey, std::vector<const pjson::value_variant*>& results, std::vector<const pjson::value_variant*>& alt_results) const
{
assert(m_name_hashtab.size());
std::string key(pKey);
for (char& c : key)
c = utolower(c);
const uint32_t hash_val = (hash_hsieh((const uint8_t *)key.c_str(), key.size()) * HASH_FMAGIC) >> HASH_SHIFT;
results.resize(0);
alt_results.resize(0);
const uint_vec& bucket = m_name_hashtab[hash_val];
for (uint32_t i = 0; i < bucket.size(); i++)
{
const uint32_t rec_index = bucket[i];
const pjson::value_variant* pObj = &m_doc[rec_index];
const char *pName = pObj->find_string_ptr("name");
const char* pPlainName = pObj->find_string_ptr("plainname");
if ((_stricmp(pKey, pName) != 0) && (_stricmp(pKey, pPlainName) != 0))
{
const std::string alt_names(pObj->find_string_obj("altnames"));
string_vec alt_tokens;
string_tokenize(alt_names, ",", "", alt_tokens);
uint32_t j;
for (j = 0; j < alt_tokens.size(); j++)
if (string_icompare(alt_tokens[j], pKey) == 0)
break;
if (j < alt_tokens.size())
alt_results.push_back(pObj);
}
else
{
results.push_back(pObj);
}
}
}
const pjson::document& get_doc() const { return m_doc; }
struct geo_result
{
const pjson::value_variant* m_pVariant;
bool m_alt;
};
typedef std::vector<geo_result> geo_result_vec;
enum { MAX_ADMINS = 4 };
uint32_t count_admins(const pjson::value_variant* p) const
{
uint32_t num_admins;
for (num_admins = 0; num_admins < MAX_ADMINS; num_admins++)
{
std::string str(p->find_string_obj(string_format("a%u", num_admins + 1).c_str()));
if (!str.size() || (str == "00"))
break;
}
return num_admins;
}
bool is_valid_parent(const pjson::value_variant* pParent, const pjson::value_variant* pChild) const
{
if (pParent == pChild)
return false;
if (pParent->find_string_obj("ccode") != pChild->find_string_obj("ccode"))
return false;
const int parent_id = pParent->find_int32("id");
const auto find_res = m_geo_hierarchy.find(parent_id);
if (find_res != m_geo_hierarchy.end())
{
const int child_id = pChild->find_int32("id");